#!/usr/bin/env python3
"""
BNKFX Admin Module for Preview Server
Handles Payment Methods, User Management, Impersonation, KYC & Balance Adjustments.
"""

import json
import time
import urllib.parse
import hashlib
import html as html_lib
import mail_service
import platform_settings_service

def handle_admin_post(handler, parsed, data, STATE):
    path = parsed.path

    # 1. Create Payment Method
    if path == "/admin/payment-methods":
        new_id = len(STATE.get("payment_methods", [])) + 1
        code = str(data.get("code", "USDC")).upper().strip()
        network = str(data.get("network", "ERC20")).upper().strip()
        name = str(data.get("name", f"{code} ({network})")).strip()
        wallet = str(data.get("wallet_address", "")).strip()

        # Determine icon URL (use uploaded base64 data, custom icon_url or fallback to SVG)
        icon_data = data.get("icon_data", "")
        icon_mime = data.get("icon_mime", "image/png")
        if icon_data:
            icon_url = f"/admin/uploads/icon/{new_id}"
        else:
            icon_url = data.get("icon_url") or f"/assets/images/crypto/{code.lower()}.svg"

        # QR code settings
        qr_enabled = str(data.get("qr_enabled", "1")) == "1"
        qr_type = str(data.get("qr_type", "auto"))  # "auto", "upload", "none"
        qr_data = data.get("qr_data", "")  # base64 uploaded QR if qr_type == "upload"

        try:
            min_dep = float(data.get("min_deposit", 50.0))
        except (ValueError, TypeError):
            min_dep = 50.0

        try:
            max_dep = float(data.get("max_deposit", 100000.0))
        except (ValueError, TypeError):
            max_dep = 100000.0

        try:
            confs = int(data.get("required_confirmations", 12))
        except (ValueError, TypeError):
            confs = 12

        try:
            fee_pct = float(data.get("processing_fee_pct", 0.0))
        except (ValueError, TypeError):
            fee_pct = 0.0

        try:
            sort_order = int(data.get("sort_order", new_id))
        except (ValueError, TypeError):
            sort_order = new_id

        new_pm = {
            "id": new_id,
            "name": name,
            "code": code,
            "network": network,
            "icon_url": icon_url,
            "icon_data": icon_data if icon_data else "",
            "icon_mime": icon_mime,
            "wallet_address": wallet,
            "min_deposit": min_dep,
            "max_deposit": max_dep,
            "required_confirmations": confs,
            "processing_fee_pct": fee_pct,
            "instructions": str(data.get("instructions", "")).strip(),
            "status": str(data.get("status", "active")),
            "sort_order": sort_order,
            "payment_type": str(data.get("payment_type", "cryptocurrency")),
            "processing_time": str(data.get("processing_time", "3 - 8 mins")).strip() or "3 - 8 mins",
            "notes": str(data.get("notes", "")).strip(),
            "qr_enabled": qr_enabled,
            "qr_type": qr_type,
            "qr_data": qr_data
        }
        STATE.setdefault("payment_methods", []).append(new_pm)
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_payment_method_created",
            "user_id": 1,
            "ip_address": "127.0.0.1",
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Created payment method {new_pm['name']} ({code} {network})"
        })
        handler.send_response(302)
        handler.send_header("Location", "/admin/payment-methods")
        handler.end_headers()
        return True

    # 2. Update Payment Method
    if path.startswith("/admin/payment-methods/") and path.endswith("/update"):
        pm_id = int(path.split("/")[3])
        pm = next((p for p in STATE.get("payment_methods", []) if p["id"] == pm_id), None)
        if pm:
            new_addr = str(data.get("wallet_address", pm["wallet_address"])).strip()
            if new_addr and new_addr != pm["wallet_address"]:
                STATE.setdefault("wallet_address_history", []).append({
                    "payment_method_id": pm_id,
                    "old_address": pm["wallet_address"],
                    "new_address": new_addr,
                    "reason": data.get("change_reason", "Administrative wallet rotation"),
                    "changed_by": 1,
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
                })
                STATE.setdefault("audit_logs", []).append({
                    "action": "admin_wallet_address_updated",
                    "user_id": 1,
                    "ip_address": "127.0.0.1",
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                    "details": f"Address updated for {pm['name']}: {new_addr}"
                })
                pm["wallet_address"] = new_addr

            if data.get("name"):
                pm["name"] = str(data["name"]).strip()
            if data.get("code"):
                pm["code"] = str(data["code"]).upper().strip()
            if data.get("network"):
                pm["network"] = str(data["network"]).upper().strip()

            if "min_deposit" in data and str(data["min_deposit"]).strip() != "":
                try:
                    pm["min_deposit"] = float(data["min_deposit"])
                except (ValueError, TypeError):
                    pass

            if "max_deposit" in data and str(data["max_deposit"]).strip() != "":
                try:
                    pm["max_deposit"] = float(data["max_deposit"])
                except (ValueError, TypeError):
                    pass

            if "required_confirmations" in data and str(data["required_confirmations"]).strip() != "":
                try:
                    pm["required_confirmations"] = int(data["required_confirmations"])
                except (ValueError, TypeError):
                    pass

            if "processing_fee_pct" in data and str(data["processing_fee_pct"]).strip() != "":
                try:
                    pm["processing_fee_pct"] = float(data["processing_fee_pct"])
                except (ValueError, TypeError):
                    pass

            if "instructions" in data:
                pm["instructions"] = str(data.get("instructions", "")).strip()

            if "status" in data and data["status"]:
                pm["status"] = str(data["status"])

            if "processing_time" in data and str(data["processing_time"]).strip():
                pm["processing_time"] = str(data["processing_time"]).strip()

            if "sort_order" in data and str(data["sort_order"]).strip() != "":
                try:
                    pm["sort_order"] = int(data["sort_order"])
                except (ValueError, TypeError):
                    pass

            if "notes" in data:
                pm["notes"] = str(data.get("notes", "")).strip()

            # Preserve existing icon if no new icon uploaded
            if data.get("icon_data"):
                pm["icon_data"] = data["icon_data"]
                pm["icon_mime"] = data.get("icon_mime", "image/png")
                pm["icon_url"] = f"/admin/uploads/icon/{pm_id}"
            elif data.get("icon_url"):
                pm["icon_url"] = data["icon_url"]

            # QR Code preservation & update
            if "qr_enabled" in data:
                pm["qr_enabled"] = str(data.get("qr_enabled", "1")) == "1"
            if "qr_type" in data:
                pm["qr_type"] = str(data.get("qr_type", pm.get("qr_type", "auto")))
            if data.get("qr_data"):
                pm["qr_data"] = data["qr_data"]

            STATE.setdefault("audit_logs", []).append({
                "action": "admin_payment_method_updated",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Payment method #{pm_id} ({pm['name']}) updated: limits ${pm['min_deposit']:.2f}-${pm['max_deposit']:.2f}, status {pm['status']}"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/payment-methods")
        handler.end_headers()
        return True

    # 3. Toggle Status Payment Method
    if path.startswith("/admin/payment-methods/") and path.endswith("/toggle-status"):
        pm_id = int(path.split("/")[3])
        pm = next((p for p in STATE.get("payment_methods", []) if p["id"] == pm_id), None)
        if pm:
            pm["status"] = "disabled" if pm["status"] == "active" else "active"
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_payment_method_status_toggled",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Method {pm['name']} toggled to {pm['status']}"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/payment-methods")
        handler.end_headers()
        return True

    # 4. Delete / Archive Payment Method
    if path.startswith("/admin/payment-methods/") and path.endswith("/delete"):
        pm_id = int(path.split("/")[3])
        pm = next((p for p in STATE.get("payment_methods", []) if p["id"] == pm_id), None)
        if pm:
            pm["status"] = "archived"
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_payment_method_archived",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Payment method {pm['name']} archived"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/payment-methods")
        handler.end_headers()
        return True

    # 5. User Update Profile
    if path.startswith("/admin/users/") and path.endswith("/update-profile"):
        uid = int(path.split("/")[3])
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            target["first_name"] = str(data.get("first_name", target["first_name"]))
            target["last_name"] = str(data.get("last_name", target["last_name"]))
            target["phone"] = str(data.get("phone", target.get("phone", "")))
            target["country"] = str(data.get("country", target.get("country", "")))
            target["address"] = str(data.get("address", target.get("address", "")))
            if STATE.get("user", {}).get("id") == uid:
                STATE["user"].update(target)
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_user_profile_updated",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Updated profile for user #{uid} ({target['email']})"
            })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=profile")
        handler.end_headers()
        return True

    # 6. User Suspend / Reactivate
    if path.startswith("/admin/users/") and path.endswith("/toggle-status"):
        uid = int(path.split("/")[3])
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            if target["status"] == "active":
                target["status"] = "suspended"
                target["suspended_reason"] = str(data.get("suspend_reason", "Suspended by administrator"))
                target["suspended_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                target["status"] = "active"
                target["suspended_reason"] = None
                target["suspended_at"] = None
            if STATE.get("user", {}).get("id") == uid:
                STATE["user"]["status"] = target["status"]
                STATE["user"]["suspended_reason"] = target["suspended_reason"]
                STATE["user"]["suspended_at"] = target["suspended_at"]
            STATE.setdefault("audit_logs", []).append({
                "action": f"admin_user_{target['status']}",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"User #{uid} status changed to {target['status']}"
            })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=status")
        handler.end_headers()
        return True

    # 7. User Verify Email
    if path.startswith("/admin/users/") and path.endswith("/verify-email"):
        uid = int(path.split("/")[3])
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            target["email_verified_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            if STATE.get("user", {}).get("id") == uid:
                STATE["user"]["email_verified_at"] = target["email_verified_at"]
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_email_verified",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Email verified manually for user #{uid} ({target['email']})"
            })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=email")
        handler.end_headers()
        return True

    # 8. User Revoke Email
    if path.startswith("/admin/users/") and path.endswith("/revoke-email"):
        uid = int(path.split("/")[3])
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            target["email_verified_at"] = None
            if STATE.get("user", {}).get("id") == uid:
                STATE["user"]["email_verified_at"] = None
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_email_verification_revoked",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Email verification revoked for user #{uid} ({target['email']})"
            })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=email")
        handler.end_headers()
        return True

    # 9. User KYC Review
    if path.startswith("/admin/users/") and path.endswith("/kyc"):
        uid = int(path.split("/")[3])
        action = str(data.get("action", "approve"))
        reason = str(data.get("reason", "KYC criteria not met"))
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            if action == "approve":
                target["kyc_status"] = "approved"
                target["kyc_reviewed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
                target["kyc_rejection_reason"] = None
            else:
                target["kyc_status"] = "rejected"
                target["kyc_reviewed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
                target["kyc_rejection_reason"] = reason
            if STATE.get("user", {}).get("id") == uid:
                STATE["user"]["kyc_status"] = target["kyc_status"]
                STATE["user"]["kyc_rejection_reason"] = target["kyc_rejection_reason"]
            STATE.setdefault("audit_logs", []).append({
                "action": f"admin_kyc_{action}",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"KYC {action} for user #{uid} ({target['email']})"
            })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=kyc")
        handler.end_headers()
        return True

    # 10. Balance Adjustment (Double-Entry Ledger)
    if path.startswith("/admin/users/") and path.endswith("/adjust-balance"):
        uid = int(path.split("/")[3])
        direction = str(data.get("direction", "credit")).lower()
        amt = float(data.get("amount", 0.0))
        reason = str(data.get("reason", "Administrative balance adjustment"))
        allow_overdraft = bool(data.get("allow_overdraft", False))
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)

        if direction == "debit" and STATE["accounts"][0]["balance"] < amt and not allow_overdraft:
            res = {"success": False, "error": f"Insufficient funds for debit. Current balance is ${STATE['accounts'][0]['balance']:.2f} USD."}
            handler.send_response(400)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps(res).encode('utf-8'))
            return True

        if direction == "credit":
            STATE["accounts"][0]["balance"] += amt
        else:
            STATE["accounts"][0]["balance"] -= amt

        ref = "ADJ-" + hashlib.sha256(str(time.time()).encode()).hexdigest()[:8].upper()
        adj_tx = {
            "ref": ref,
            "direction": direction,
            "sender": "System Operational Reserve Vault",
            "sender_email": "vault@bnkfx.internal",
            "recipient": f"{target['first_name']} {target['last_name']}" if target else "Customer",
            "recipient_email": target["email"] if target else "customer@bnkfx.com",
            "amount": amt,
            "currency": "USD",
            "fee": 0.00,
            "status": "Completed",
            "date": "Just now",
            "reason": reason
        }
        STATE["transfers"].insert(0, adj_tx)
        STATE.setdefault("audit_logs", []).append({
            "action": f"admin_balance_{direction}",
            "user_id": 1,
            "ip_address": "127.0.0.1",
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Balance {direction} of ${amt:.2f} USD posted for user #{uid}. New balance: ${STATE['accounts'][0]['balance']:.2f}"
        })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{uid}?tab=balance")
        handler.end_headers()
        return True

    # 11. Impersonate User
    if path.startswith("/admin/impersonate/") and not path.endswith("/exit"):
        uid = int(path.split("/")[3])
        target = next((u for u in STATE.get("users", []) if u["id"] == uid), None)
        if target:
            STATE["impersonation"] = {
                "original_admin_id": 1,
                "original_admin_email": "admin@bnkfx.com",
                "impersonated_user_id": target["id"],
                "impersonated_user_email": target["email"],
                "started_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "reason": str(data.get("impersonate_reason", "Customer troubleshooting"))
            }
            STATE["user"] = target
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_user_impersonation_started",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Support session started: logged in as {target['email']}"
            })
        handler.send_response(302)
        handler.send_header("Location", "/dashboard")
        handler.end_headers()
        return True

    # 10. KYC Management: Start Review
    if path.startswith("/admin/kyc/") and path.endswith("/start-review"):
        sub_id = int(path.split("/")[3])
        sub = next((k for k in STATE.get("kyc_verifications", []) if k["id"] == sub_id), None)
        if sub:
            sub["status"] = "under_review"
            sub["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            target_user = next((u for u in STATE.get("users", []) if u["id"] == sub["user_id"]), None)
            if target_user:
                target_user["kyc_status"] = "under_review"
                if STATE.get("user", {}).get("id") == target_user["id"]:
                    STATE["user"]["kyc_status"] = "under_review"
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_kyc_start_review",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Compliance review started for KYC submission #{sub_id} (User #{sub['user_id']})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/kyc")
        handler.end_headers()
        return True

    # 11. KYC Management: Approve
    if path.startswith("/admin/kyc/") and path.endswith("/approve"):
        sub_id = int(path.split("/")[3])
        sub = next((k for k in STATE.get("kyc_verifications", []) if k["id"] == sub_id), None)
        if sub:
            sub["status"] = "approved"
            sub["reviewed_by"] = 1
            sub["reviewed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            sub["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            sub["rejection_reason"] = None
            notes = str(data.get("notes", "")).strip()
            if notes:
                sub["notes"] = notes
            target_user = next((u for u in STATE.get("users", []) if u["id"] == sub["user_id"]), None)
            if target_user:
                target_user["kyc_status"] = "approved"
                target_user["kyc_reviewed_at"] = sub["reviewed_at"]
                target_user["kyc_rejection_reason"] = None
                if STATE.get("user", {}).get("id") == target_user["id"]:
                    STATE["user"]["kyc_status"] = "approved"
                    STATE["user"]["kyc_reviewed_at"] = sub["reviewed_at"]
                    STATE["user"]["kyc_rejection_reason"] = None
            for acc in STATE.get("accounts", []):
                acc["verification_status"] = "verified"
            # Record approval email
            user_email = target_user["email"] if target_user else "customer@bnkfx.com"
            user_name = f"{target_user['first_name']} {target_user['last_name']}" if target_user else "Customer"
            STATE.setdefault("email_logs", []).append({
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": sub["user_id"],
                "recipient": user_email,
                "subject": "Your Identity Verification Is Complete",
                "template": "kyc_approved",
                "status": "sent",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_kyc_approved",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Approved KYC submission #{sub_id} for {user_name} ({user_email})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/kyc")
        handler.end_headers()
        return True

    # 12. KYC Management: Reject
    if path.startswith("/admin/kyc/") and path.endswith("/reject"):
        sub_id = int(path.split("/")[3])
        sub = next((k for k in STATE.get("kyc_verifications", []) if k["id"] == sub_id), None)
        reason = str(data.get("reason", "Incomplete or unverified identity documentation")).strip()
        if sub:
            sub["status"] = "rejected"
            sub["rejection_reason"] = reason
            sub["reviewed_by"] = 1
            sub["reviewed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            sub["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            target_user = next((u for u in STATE.get("users", []) if u["id"] == sub["user_id"]), None)
            if target_user:
                target_user["kyc_status"] = "rejected"
                target_user["kyc_rejection_reason"] = reason
                target_user["kyc_reviewed_at"] = sub["reviewed_at"]
                if STATE.get("user", {}).get("id") == target_user["id"]:
                    STATE["user"]["kyc_status"] = "rejected"
                    STATE["user"]["kyc_rejection_reason"] = reason
                    STATE["user"]["kyc_reviewed_at"] = sub["reviewed_at"]
            # Record rejection email
            user_email = target_user["email"] if target_user else "customer@bnkfx.com"
            user_name = f"{target_user['first_name']} {target_user['last_name']}" if target_user else "Customer"
            STATE.setdefault("email_logs", []).append({
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": sub["user_id"],
                "recipient": user_email,
                "subject": "Identity Verification Requires Attention — Alliance Bank",
                "template": "kyc_rejected",
                "status": "sent",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_kyc_rejected",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Rejected KYC submission #{sub_id} for {user_name} (Reason: {reason})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/kyc")
        handler.end_headers()
        return True

    # 13. KYC Management: Request Additional Info
    if path.startswith("/admin/kyc/") and path.endswith("/request-info"):
        sub_id = int(path.split("/")[3])
        sub = next((k for k in STATE.get("kyc_verifications", []) if k["id"] == sub_id), None)
        notes = str(data.get("notes", "Please upload a clearer image of your document.")).strip()
        if sub:
            sub["status"] = "additional_info_required"
            sub["notes"] = notes
            sub["reviewed_by"] = 1
            sub["reviewed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            sub["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            target_user = next((u for u in STATE.get("users", []) if u["id"] == sub["user_id"]), None)
            if target_user:
                target_user["kyc_status"] = "additional_info_required"
                target_user["kyc_notes"] = notes
                target_user["kyc_reviewed_at"] = sub["reviewed_at"]
                if STATE.get("user", {}).get("id") == target_user["id"]:
                    STATE["user"]["kyc_status"] = "additional_info_required"
                    STATE["user"]["kyc_notes"] = notes
                    STATE["user"]["kyc_reviewed_at"] = sub["reviewed_at"]
            # Record email
            user_email = target_user["email"] if target_user else "customer@bnkfx.com"
            user_name = f"{target_user['first_name']} {target_user['last_name']}" if target_user else "Customer"
            STATE.setdefault("email_logs", []).append({
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": sub["user_id"],
                "recipient": user_email,
                "subject": "Additional Information Required for Verification",
                "template": "kyc_additional_info",
                "status": "sent",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_kyc_request_info",
                "user_id": 1,
                "ip_address": "127.0.0.1",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Requested additional info on KYC submission #{sub_id} for {user_name} ({notes})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/kyc")
        handler.end_headers()
        return True

    # 5. Create Stock
    if path == "/admin/stocks":
        new_id = len(STATE.get("stocks", [])) + 1
        name = str(data.get("name", "")).strip()
        ticker = str(data.get("ticker", "")).strip().upper()
        category = str(data.get("category", "Technology")).strip()
        desc = str(data.get("short_description", "")).strip()
        def_plan = int(data.get("default_plan_id") or 3)
        status = str(data.get("status", "active")).strip()
        order = int(data.get("display_order") or 0)
        logo_url = str(data.get("logo_url") or f"/assets/images/stocks/{ticker.lower()}.svg").strip()
        notes = str(data.get("notes", "")).strip()

        new_stk = {
            "id": new_id,
            "name": name,
            "ticker": ticker,
            "category": category,
            "short_description": desc,
            "default_plan_id": def_plan,
            "status": status,
            "logo_url": logo_url,
            "display_order": order,
            "notes": notes
        }
        STATE.setdefault("stocks", []).append(new_stk)
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_stock_created",
            "user_id": 1,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Created stock {ticker} ({name})"
        })
        handler.send_response(302)
        handler.send_header("Location", "/admin/stocks")
        handler.end_headers()
        return True

    # 6. Update Stock
    if path.startswith("/admin/stocks/") and path.endswith("/update"):
        parts = path.strip("/").split("/")
        stk_id = int(parts[2])
        stk = next((s for s in STATE.get("stocks", []) if s["id"] == stk_id), None)
        if stk:
            if "name" in data: stk["name"] = str(data["name"]).strip()
            if "ticker" in data: stk["ticker"] = str(data["ticker"]).strip().upper()
            if "category" in data: stk["category"] = str(data["category"]).strip()
            if "short_description" in data: stk["short_description"] = str(data["short_description"]).strip()
            if "default_plan_id" in data and data["default_plan_id"]: stk["default_plan_id"] = int(data["default_plan_id"])
            if "status" in data: stk["status"] = str(data["status"]).strip()
            if "display_order" in data: stk["display_order"] = int(data["display_order"] or 0)
            if "logo_url" in data and data["logo_url"]: stk["logo_url"] = str(data["logo_url"]).strip()
            if "notes" in data: stk["notes"] = str(data["notes"]).strip()

            STATE.setdefault("audit_logs", []).append({
                "action": "admin_stock_updated",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Updated stock {stk['ticker']} (ID: {stk_id})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/stocks")
        handler.end_headers()
        return True

    # 7. Toggle Stock Status
    if path.startswith("/admin/stocks/") and path.endswith("/toggle-status"):
        parts = path.strip("/").split("/")
        stk_id = int(parts[2])
        stk = next((s for s in STATE.get("stocks", []) if s["id"] == stk_id), None)
        if stk:
            stk["status"] = "inactive" if stk["status"] == "active" else "active"
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_stock_status_toggled",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Toggled status of stock {stk['ticker']} to {stk['status']}"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/stocks")
        handler.end_headers()
        return True

    # 8. Delete Stock
    if path.startswith("/admin/stocks/") and path.endswith("/delete"):
        parts = path.strip("/").split("/")
        stk_id = int(parts[2])
        stk = next((s for s in STATE.get("stocks", []) if s["id"] == stk_id), None)
        if stk:
            STATE["stocks"] = [s for s in STATE.get("stocks", []) if s["id"] != stk_id]
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_stock_deleted",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Deleted stock {stk['ticker']} (ID: {stk_id})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/stocks")
        handler.end_headers()
        return True

    # 9. Create Plan
    if path == "/admin/plans":
        new_id = len(STATE.get("investment_plans", [])) + 1
        name = str(data.get("name", "")).strip()
        slug = name.lower().replace(" ", "-")
        min_amt = float(data.get("min_amount") or 50.0)
        is_unl = str(data.get("is_unlimited", "0")) in ["1", "true", "True"] or (data.get("max_amount") in ["", None])
        max_amt = None if is_unl else float(data.get("max_amount") or 100.0)
        duration = int(data.get("duration_hours") or 48)
        ret_pct = float(data.get("return_percentage") or 20.0)
        is_rec = str(data.get("is_recommended", "0")) in ["1", "true", "True"]

        new_plan = {
            "id": new_id,
            "name": name,
            "slug": slug,
            "description": f"{name} yield product tier.",
            "min_amount": min_amt,
            "max_amount": max_amt,
            "is_unlimited": is_unl,
            "duration_hours": duration,
            "return_percentage": ret_pct,
            "is_recommended": is_rec,
            "status": "active",
            "display_order": new_id
        }
        STATE.setdefault("investment_plans", []).append(new_plan)
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_plan_created",
            "user_id": 1,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Created plan {name} (+{ret_pct}%, {duration}h)"
        })
        handler.send_response(302)
        handler.send_header("Location", "/admin/plans")
        handler.end_headers()
        return True

    # 10. Update Plan
    if path.startswith("/admin/plans/") and path.endswith("/update"):
        parts = path.strip("/").split("/")
        plan_id = int(parts[2])
        plan = next((p for p in STATE.get("investment_plans", []) if p["id"] == plan_id), None)
        if plan:
            if "name" in data: plan["name"] = str(data["name"]).strip()
            if "min_amount" in data and data["min_amount"]: plan["min_amount"] = float(data["min_amount"])
            is_unl = str(data.get("is_unlimited", "0")) in ["1", "true", "True"] or (data.get("max_amount") in ["", None])
            plan["is_unlimited"] = is_unl
            plan["max_amount"] = None if is_unl else (float(data["max_amount"]) if data.get("max_amount") else None)
            if "duration_hours" in data and data["duration_hours"]: plan["duration_hours"] = int(data["duration_hours"])
            if "return_percentage" in data and data["return_percentage"]: plan["return_percentage"] = float(data["return_percentage"])
            if "is_recommended" in data: plan["is_recommended"] = str(data["is_recommended"]) in ["1", "true", "True"]

            STATE.setdefault("audit_logs", []).append({
                "action": "admin_plan_updated",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Updated plan {plan['name']} (ID: {plan_id})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/plans")
        handler.end_headers()
        return True

    # 11. Toggle Plan Status
    if path.startswith("/admin/plans/") and path.endswith("/toggle-status"):
        parts = path.strip("/").split("/")
        plan_id = int(parts[2])
        plan = next((p for p in STATE.get("investment_plans", []) if p["id"] == plan_id), None)
        if plan:
            plan["status"] = "inactive" if plan["status"] == "active" else "active"
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_plan_status_toggled",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Toggled status of plan {plan['name']} to {plan['status']}"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/plans")
        handler.end_headers()
        return True

    # 12. Create Card Product
    if path == "/admin/cards/products":
        new_id = max([p["id"] for p in STATE.get("card_products", [])] + [0]) + 1
        name = str(data.get("name", "New Card Product")).strip()
        slug = str(data.get("slug", name.lower().replace(" ", "-"))).strip()
        card_type = str(data.get("card_type", "virtual")).strip()
        network = str(data.get("network", "Visa")).strip()
        design = str(data.get("card_design", "obsidian")).strip()
        fee = float(data.get("issuance_fee", 0.0))
        min_bal = float(data.get("min_balance_required", 0.0))
        daily_lim = float(data.get("daily_limit", 5000.0))
        monthly_lim = float(data.get("monthly_limit", 25000.0))
        description = str(data.get("description", "")).strip()
        is_active = int(data.get("is_active", 1))

        feats_raw = data.get("features", "")
        if isinstance(feats_raw, list):
            features = feats_raw
        else:
            features = [f.strip() for f in str(feats_raw).replace("\r", "").split("\n") if f.strip()]

        new_prod = {
            "id": new_id,
            "name": name,
            "slug": slug,
            "type": card_type,
            "card_type": card_type,
            "network": network,
            "design": design,
            "card_design": design,
            "fee": fee,
            "issuance_fee": fee,
            "min_balance_required": min_bal,
            "limit": daily_lim,
            "daily_limit": daily_lim,
            "monthly_limit": monthly_lim,
            "description": description,
            "features": features,
            "is_active": is_active
        }
        STATE.setdefault("card_products", []).append(new_prod)
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_card_product_created",
            "user_id": 1,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Created card product '{name}' (ID: {new_id}, Fee: ${fee:.2f})"
        })
        handler.send_response(302)
        handler.send_header("Location", "/admin/cards?tab=products")
        handler.end_headers()
        return True

    # 13. Update Card Product
    if path.startswith("/admin/cards/products/") and path.endswith("/update"):
        parts = path.strip("/").split("/")
        prod_id = int(parts[3])
        prod = next((p for p in STATE.get("card_products", []) if p["id"] == prod_id), None)
        if prod:
            if "name" in data: prod["name"] = str(data["name"]).strip()
            if "card_type" in data: prod["card_type"] = prod["type"] = str(data["card_type"]).strip()
            if "network" in data: prod["network"] = str(data["network"]).strip()
            if "card_design" in data: prod["card_design"] = prod["design"] = str(data["card_design"]).strip()
            if "issuance_fee" in data: prod["issuance_fee"] = prod["fee"] = float(data["issuance_fee"])
            if "min_balance_required" in data: prod["min_balance_required"] = float(data["min_balance_required"])
            if "daily_limit" in data: prod["daily_limit"] = prod["limit"] = float(data["daily_limit"])
            if "monthly_limit" in data: prod["monthly_limit"] = float(data["monthly_limit"])
            if "description" in data: prod["description"] = str(data["description"]).strip()
            if "is_active" in data: prod["is_active"] = int(data["is_active"])
            if "features" in data:
                feats_raw = data["features"]
                if isinstance(feats_raw, list):
                    prod["features"] = feats_raw
                else:
                    prod["features"] = [f.strip() for f in str(feats_raw).replace("\r", "").split("\n") if f.strip()]

            STATE.setdefault("audit_logs", []).append({
                "action": "admin_card_product_updated",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Updated card product '{prod['name']}' (ID: {prod_id})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/cards?tab=products")
        handler.end_headers()
        return True

    # 14. Toggle Card Product Status
    if path.startswith("/admin/cards/products/") and path.endswith("/toggle-status"):
        parts = path.strip("/").split("/")
        prod_id = int(parts[3])
        prod = next((p for p in STATE.get("card_products", []) if p["id"] == prod_id), None)
        if prod:
            prod["is_active"] = 0 if prod.get("is_active", 1) == 1 else 1
            status_str = "activated" if prod["is_active"] == 1 else "deactivated"
            STATE.setdefault("audit_logs", []).append({
                "action": f"admin_card_product_{status_str}",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"{status_str.capitalize()} card product '{prod['name']}' (ID: {prod_id})"
            })
        handler.send_response(302)
        handler.send_header("Location", "/admin/cards?tab=products")
        handler.end_headers()
        return True

    # 15. Approve Card Application
    if (path.startswith("/admin/cards/applications/") or path.startswith("/admin/cards/orders/")) and path.endswith("/approve"):
        parts = path.strip("/").split("/")
        order_id = int(parts[3])
        order = next((o for o in STATE.get("card_orders", []) if o["id"] == order_id), None)
        if order and order.get("status") in ["pending", "processing"]:
            order["status"] = "completed"
            order["approved_at"] = time.strftime("%Y-%m-%d %H:%M:%S")

            # Issue the actual card into STATE["cards"]
            new_id = max([c["id"] for c in STATE.get("cards", [])] + [0]) + 1
            import random
            last_4 = str(random.randint(1000, 9999))
            holder_name = str(order.get("user_name", "ELOCHUKWU ELOM")).upper()
            prod = next((p for p in STATE.get("card_products", []) if p["id"] == order.get("product_id")), None)
            daily_lim = prod["limit"] if prod else 5000.0

            issued = {
                "id": new_id,
                "name": order.get("product_name", "Bnkfx Card"),
                "product_name": order.get("product_name", "Bnkfx Card"),
                "type": order.get("card_type", "virtual"),
                "card_type": order.get("card_type", "virtual"),
                "network": order.get("network", "Visa"),
                "design": order.get("card_design", "obsidian"),
                "card_design": order.get("card_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": daily_lim,
                "spent_today": 0.0,
                "currency": "USD",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            STATE.setdefault("cards", []).append(issued)
            STATE.setdefault("audit_logs", []).append({
                "action": "admin_card_application_approved",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Approved card order {order.get('reference', order_id)} and issued {issued['name']} ending in {last_4}"
            })

        if handler.headers.get("X-Requested-With") == "XMLHttpRequest" or "application/json" in handler.headers.get("Accept", ""):
            handler.send_response(200)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({"success": True, "message": "Card application approved and issued successfully."}).encode('utf-8'))
            return True

        handler.send_response(302)
        handler.send_header("Location", "/admin/cards?tab=applications")
        handler.end_headers()
        return True

    # 16. Reject Card Application
    if (path.startswith("/admin/cards/applications/") or path.startswith("/admin/cards/orders/")) and path.endswith("/reject"):
        parts = path.strip("/").split("/")
        order_id = int(parts[3])
        order = next((o for o in STATE.get("card_orders", []) if o["id"] == order_id), None)
        if order and order.get("status") in ["pending", "processing"]:
            reason = str(data.get("reason", "Application did not meet compliance criteria.")).strip()
            order["status"] = "rejected"
            order["rejection_reason"] = reason
            order["rejected_at"] = time.strftime("%Y-%m-%d %H:%M:%S")

            # Refund fee if fee was paid
            fee_paid = float(order.get("payment_amount", 0.0))
            if fee_paid > 0:
                STATE["accounts"][0]["balance"] += fee_paid
                STATE.setdefault("transactions", []).insert(0, {
                    "id": len(STATE.get("transactions", [])) + 1,
                    "type": "credit",
                    "category": "card_refund",
                    "amount": fee_paid,
                    "currency": "USD",
                    "status": "completed",
                    "reference": f"REF-CARD-{order_id}",
                    "description": f"Refund: Card Issuance Fee - {order.get('product_name', 'Virtual Card')}",
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
                })

            STATE.setdefault("audit_logs", []).append({
                "action": "admin_card_application_rejected",
                "user_id": 1,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "details": f"Rejected card order {order.get('reference', order_id)}. Reason: {reason}. Refund: ${fee_paid:.2f}"
            })

        if handler.headers.get("X-Requested-With") == "XMLHttpRequest" or "application/json" in handler.headers.get("Accept", ""):
            handler.send_response(200)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({"success": True, "message": "Card application rejected and fee refunded."}).encode('utf-8'))
            return True

        handler.send_response(302)
        handler.send_header("Location", "/admin/cards?tab=applications")
        handler.end_headers()
        return True

    # 13. Update Email Settings
    if path in ["/admin/settings/email", "/admin/email-settings"]:
        settings = mail_service.get_email_settings(STATE)
        
        # Text fields
        if "smtp_host" in data and str(data["smtp_host"]).strip():
            settings["smtp_host"] = str(data["smtp_host"]).strip()
        if "smtp_port" in data:
            try:
                settings["smtp_port"] = int(data["smtp_port"])
            except (ValueError, TypeError):
                pass
        if "smtp_username" in data and str(data["smtp_username"]).strip():
            settings["smtp_username"] = str(data["smtp_username"]).strip()
        
        # Password handling: only update if non-empty and not masked
        pwd_val = str(data.get("smtp_password", "")).strip()
        if pwd_val and pwd_val != "••••••••••••":
            settings["smtp_password"] = pwd_val
            
        if "encryption" in data:
            enc = str(data["encryption"]).lower().strip()
            if enc in ["tls", "ssl", "none"]:
                settings["encryption"] = enc
        if "from_name" in data and str(data["from_name"]).strip():
            settings["from_name"] = str(data["from_name"]).strip()
        if "from_address" in data and str(data["from_address"]).strip():
            settings["from_address"] = str(data["from_address"]).strip()
            
        # Booleans / Toggles
        def parse_bool(val, default=False):
            if val is None:
                return default
            return str(val).lower() in ["1", "true", "on", "yes"]

        is_form_submit = (handler.headers.get("Content-Type", "").startswith("application/x-www-form-urlencoded"))
        if is_form_submit:
            settings["require_email_verification"] = ("require_email_verification" in data)
            settings["notify_welcome"] = ("notify_welcome" in data)
            settings["notify_transactions"] = ("notify_transactions" in data)
            settings["notify_security"] = ("notify_security" in data)
            settings["notify_password_reset"] = ("notify_password_reset" in data)
            settings["notify_deposits"] = ("notify_deposits" in data)
            settings["notify_withdrawals"] = ("notify_withdrawals" in data)
            settings["notify_cards"] = ("notify_cards" in data)
        else:
            for k in ["require_email_verification", "notify_welcome", "notify_transactions", "notify_security",
                      "notify_password_reset", "notify_deposits", "notify_withdrawals", "notify_cards"]:
                if k in data:
                    settings[k] = parse_bool(data[k])

        STATE["email_settings"] = settings
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_email_settings_updated",
            "user_id": 1,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Updated SMTP and notification trigger configuration (Host: {settings['smtp_host']}:{settings['smtp_port']}, Enc: {settings['encryption']})"
        })

        if handler.headers.get("X-Requested-With") == "XMLHttpRequest" or "application/json" in handler.headers.get("Accept", ""):
            handler.send_response(200)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            safe_settings = dict(settings)
            safe_settings["smtp_password"] = "••••••••••••"
            handler.wfile.write(json.dumps({"success": True, "message": "Email settings saved successfully.", "settings": safe_settings}).encode('utf-8'))
            return True

        handler.send_response(302)
        handler.send_header("Location", "/admin/settings/email?saved=1")
        handler.end_headers()
        return True

    # 14. Admin Send Test Email
    if path in ["/admin/settings/email/test", "/admin/email-settings/test"]:
        recipient = str(data.get("recipient_email") or data.get("recipient") or STATE.get("user", {}).get("email", "admin@bnkfx.com")).strip()
        settings = mail_service.get_email_settings(STATE)
        
        success = mail_service.send_notification_email(
            recipient=recipient,
            template="test",
            context={
                "host": settings.get("smtp_host", "smtp.mailgun.org"),
                "port": settings.get("smtp_port", 587),
                "encryption": settings.get("encryption", "TLS"),
                "sender": f"{settings.get('from_name', 'Alliance Bank')} <{settings.get('from_address', 'notifications@bnkfx.com')}>",
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC")
            },
            user_id=1,
            STATE=STATE
        )

        STATE.setdefault("audit_logs", []).append({
            "action": "admin_email_test_dispatched",
            "user_id": 1,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Dispatched SMTP diagnostic test email to {recipient} (Status: {'Sent' if success else 'Failed'})"
        })

        handler.send_response(200)
        handler.send_header("Content-Type", "application/json")
        handler.end_headers()
        handler.wfile.write(json.dumps({
            "success": success,
            "message": f"SMTP diagnostic test email dispatched to {recipient}." if success else "Failed to dispatch test email.",
            "recipient": recipient,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "log_id": len(STATE.get("email_logs", []))
        }).encode('utf-8'))
        return True

    # 15. Platform Settings Update (Super Admin Only)
    if path == "/admin/settings/platform":
        actor_user = STATE.get("user", {})
        if not platform_settings_service.is_super_admin(actor_user):
            handler.send_response(403)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({
                "success": False,
                "error": "Access denied. Only Super Administrators can modify global platform settings."
            }).encode('utf-8'))
            return True

        success, msg = platform_settings_service.update_platform_settings(data, STATE, actor_user)
        active_settings = platform_settings_service.get_platform_settings(STATE)

        if handler.headers.get("X-Requested-With") == "XMLHttpRequest" or "application/json" in handler.headers.get("Accept", ""):
            handler.send_response(200 if success else 400)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({
                "success": success,
                "message": msg,
                "settings": active_settings
            }).encode('utf-8'))
            return True

        handler.send_response(302)
        handler.send_header("Location", "/admin/settings/platform?saved=1")
        handler.end_headers()
        return True

    # 16. Platform Asset / Logo Upload (Super Admin Only)
    if path == "/admin/settings/upload-asset":
        actor_user = STATE.get("user", {})
        if not platform_settings_service.is_super_admin(actor_user):
            handler.send_response(403)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({
                "success": False,
                "error": "Access denied. Super Administrator privileges required."
            }).encode('utf-8'))
            return True

        asset_type = str(data.get("asset_type", "primary_logo")).strip()
        asset_data = data.get("asset_data", "")
        asset_mime = data.get("asset_mime", "image/png").lower()

        allowed_mimes = ["image/png", "image/jpeg", "image/webp", "image/svg+xml", "image/x-icon", "image/vnd.microsoft.icon"]
        if asset_mime not in allowed_mimes:
            handler.send_response(400)
            handler.send_header("Content-Type", "application/json")
            handler.end_headers()
            handler.wfile.write(json.dumps({
                "success": False,
                "error": f"Invalid asset format: {asset_mime}. Allowed types: PNG, JPEG, WebP, SVG, ICO."
            }).encode('utf-8'))
            return True

        # Construct asset path / data URL
        if asset_data:
            new_url = f"/admin/uploads/platform-asset/{asset_type}"
            STATE.setdefault("_platform_assets", {})[asset_type] = {
                "data": asset_data,
                "mime": asset_mime
            }
        else:
            new_url = str(data.get("asset_url", f"/assets/images/logo/{asset_type}.svg"))

        # Map to platform settings
        target_field = f"{asset_type}_url" if not asset_type.endswith("_url") else asset_type
        platform_settings_service.update_platform_settings({target_field: new_url}, STATE, actor_user)

        handler.send_response(200)
        handler.send_header("Content-Type", "application/json")
        handler.end_headers()
        handler.wfile.write(json.dumps({
            "success": True,
            "url": new_url,
            "asset_type": asset_type,
            "message": f"Asset '{asset_type}' updated successfully."
        }).encode('utf-8'))
        return True

    return False


def handle_admin_get(handler, parsed, path, STATE, build_admin_layout):
    # 0.1 Uploaded Platform Asset
    if path.startswith("/admin/uploads/platform-asset/"):
        try:
            asset_type = path.split("/")[-1]
            asset_rec = STATE.get("_platform_assets", {}).get(asset_type)
            if asset_rec and asset_rec.get("data"):
                import base64
                raw = asset_rec["data"]
                if isinstance(raw, bytes):
                    b = raw
                else:
                    if "," in raw:
                        raw = raw.split(",", 1)[1]
                    b = base64.b64decode(raw)
                handler.send_response(200)
                handler.send_header("Content-Type", asset_rec.get("mime", "image/png"))
                handler.send_header("Content-Length", str(len(b)))
                handler.end_headers()
                handler.wfile.write(b)
                return True
        except Exception:
            pass
        handler.send_response(404)
        handler.end_headers()
        return True

    # 0. Uploaded Payment Method Icon
    if path.startswith("/admin/uploads/icon/"):
        try:
            pm_id = int(path.split("/")[-1])
            pm = next((p for p in STATE.get("payment_methods", []) if p["id"] == pm_id), None)
            if pm and pm.get("icon_data"):
                import base64
                icon_raw = pm["icon_data"]
                if isinstance(icon_raw, bytes):
                    icon_bytes = icon_raw
                else:
                    if "," in icon_raw:
                        icon_raw = icon_raw.split(",", 1)[1]
                    icon_bytes = base64.b64decode(icon_raw)
                handler.send_response(200)
                handler.send_header("Content-Type", pm.get("icon_mime", "image/png"))
                handler.send_header("Content-Length", str(len(icon_bytes)))
                handler.end_headers()
                handler.wfile.write(icon_bytes)
                return True
        except Exception:
            pass
        handler.send_response(404)
        handler.end_headers()
        return True

    # 1. Exit Impersonation
    if path == "/admin/impersonate/exit":
        target_id = STATE.get("user", {}).get("id", 2)
        STATE["impersonation"] = None
        STATE["user"] = next((u for u in STATE.get("users", []) if u["id"] == 2), STATE["users"][0])
        STATE.setdefault("audit_logs", []).append({
            "action": "admin_user_impersonation_ended",
            "user_id": 1,
            "ip_address": "127.0.0.1",
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "details": f"Support session ended for user #{target_id}"
        })
        handler.send_response(302)
        handler.send_header("Location", f"/admin/users/{target_id}")
        handler.end_headers()
        return True

    # 2. Payment Methods Index
    if path == "/admin/payment-methods":
        pms = STATE.get("payment_methods", [])
        total_pms = len(pms)
        active_pms = sum(1 for p in pms if p.get("status") == "active")
        disabled_pms = sum(1 for p in pms if p.get("status") == "disabled")
        archived_pms = sum(1 for p in pms if p.get("status") == "archived")

        qs = urllib.parse.parse_qs(parsed.query)
        search_q = qs.get("search", [""])[0].lower()
        status_f = qs.get("status", [""])[0].lower()

        filtered_pms = []
        for p in pms:
            if status_f and p.get("status") != status_f:
                continue
            if search_q:
                if search_q not in p.get("name", "").lower() and search_q not in p.get("code", "").lower() and search_q not in p.get("wallet_address", "").lower():
                    continue
            filtered_pms.append(p)

        pm_rows = ""
        for p in filtered_pms:
            st = p.get("status", "active")
            if st == "active":
                st_badge = '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><span class="w-1.5 h-1.5 rounded-full bg-[#20C997] animate-pulse"></span>Active</span>'
            elif st == "disabled":
                st_badge = '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-[#F5B942]/10 text-[#F5B942] border border-[#F5B942]/20"><span class="w-1.5 h-1.5 rounded-full bg-[#F5B942]"></span>Disabled</span>'
            else:
                st_badge = '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-500/10 text-gray-400 border border-gray-500/20">Archived</span>'

            addr = p.get("wallet_address", "")
            addr_trunc = (addr[:10] + "..." + addr[-8:]) if len(addr) > 18 else addr

            hist_count = sum(1 for h in STATE.get("wallet_address_history", []) if h.get("payment_method_id") == p["id"])
            hist_btn = f'<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/10 text-[#F5B942] border border-amber-500/20" title="Address changed {hist_count} times"><i class="fa-solid fa-clock-rotate-left mr-0.5"></i>{hist_count}</span>' if hist_count > 0 else ''

            p_json_attr = html_lib.escape(json.dumps(p), quote=True)
            pm_rows += f"""
            <tr class="hover:bg-[#1C202A] transition-colors">
                <td class="px-4 py-3.5">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-xl bg-[#20242D] border border-[#292E38] flex items-center justify-center p-1.5 flex-shrink-0">
                            <img src="{p.get('icon_url', '/assets/images/crypto/usdc.svg')}" alt="{p['code']}" class="w-6 h-6 object-contain" onerror="this.src='/assets/images/crypto/usdc.svg'">
                        </div>
                        <div>
                            <p class="font-semibold text-white text-sm">{p['name']}</p>
                            <p class="text-xs text-[#737D90]">{p['code']} • Order #{p.get('sort_order', 1)}</p>
                        </div>
                    </div>
                </td>
                <td class="px-4 py-3.5">
                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-mono font-medium bg-[#246BFD]/10 text-[#246BFD] border border-[#246BFD]/20">{p['network']}</span>
                </td>
                <td class="px-4 py-3.5">
                    <div class="flex items-center gap-2">
                        <span class="font-mono text-xs text-white" title="{addr}">{addr_trunc}</span>
                        <button onclick="navigator.clipboard.writeText('{addr}'); this.innerHTML='<i class=\\'fa-solid fa-check text-xs\\'></i>'; setTimeout(()=>this.innerHTML='<i class=\\'fa-regular fa-copy text-xs\\'></i>',1500);" class="text-[#737D90] hover:text-[#246BFD] p-1"><i class="fa-regular fa-copy text-xs"></i></button>
                        {hist_btn}
                    </div>
                </td>
                <td class="px-4 py-3.5 text-xs text-white font-medium">${p['min_deposit']:.2f} - ${p['max_deposit']:,.0f} USD</td>
                <td class="px-4 py-3.5 text-xs text-[#9CA6BA]">{p['required_confirmations']} blocks • {p.get('processing_fee_pct', 0):.1f}% fee</td>
                <td class="px-4 py-3.5">{st_badge}</td>
                <td class="px-4 py-3.5 text-right">
                    <div class="inline-flex items-center gap-1.5">
                        <button type="button" data-pm="{p_json_attr}" onclick="openEditModal(JSON.parse(this.dataset.pm))" class="px-2.5 py-1.5 rounded-lg bg-[#246BFD]/10 hover:bg-[#246BFD]/20 text-[#246BFD] text-xs font-medium transition-colors" title="Edit">
                            <i class="fa-solid fa-pen-to-square"></i>
                        </button>
                        <form method="POST" action="/admin/payment-methods/{p['id']}/toggle-status" class="inline">
                            <button type="submit" class="px-2.5 py-1.5 rounded-lg {'bg-amber-500/10 text-[#F5B942]' if p['status'] == 'active' else 'bg-[#20C997]/10 text-[#20C997]'} text-xs font-medium" title="Toggle Status">
                                <i class="fa-solid {'fa-pause' if p['status'] == 'active' else 'fa-play'}"></i>
                            </button>
                        </form>
                        <form method="POST" action="/admin/payment-methods/{p['id']}/delete" class="inline" onsubmit="return confirm('Archive {p['name']}?');">
                            <button type="submit" class="px-2.5 py-1.5 rounded-lg bg-[#F05D6C]/10 text-[#F05D6C] text-xs font-medium" title="Archive">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        </form>
                    </div>
                </td>
            </tr>"""

        body = f'''<div class="space-y-6">
            <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-[#737D90] mb-1">
                        <a href="/admin" class="hover:text-white transition-colors">Admin</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <span class="text-white">Payment Methods</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Payment Methods & Deposit Wallets</h1>
                    <p class="text-xs text-[#9CA6BA] mt-0.5">Manage customer cryptocurrency deposit assets, network wallet addresses, deposit limits, and confirmations.</p>
                </div>
                <div>
                    <button onclick="document.getElementById('addMethodModal').classList.remove('hidden')" class="inline-flex items-center gap-2 px-4 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>Add Payment Method</span>
                    </button>
                </div>
            </div>

            <!-- 4 Summary KPI Cards -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-xs font-medium text-[#737D90] uppercase tracking-wider block mb-1">Total Configured</span>
                    <p class="text-2xl font-bold text-white">{total_pms}</p>
                    <span class="text-[11px] text-[#9CA6BA]">Configured methods</span>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-xs font-medium text-[#20C997] uppercase tracking-wider block mb-1">Active for Deposits</span>
                    <p class="text-2xl font-bold text-[#20C997]">{active_pms}</p>
                    <span class="text-[11px] text-[#9CA6BA]">Live on customer app</span>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-xs font-medium text-[#F5B942] uppercase tracking-wider block mb-1">Disabled Methods</span>
                    <p class="text-2xl font-bold text-[#F5B942]">{disabled_pms}</p>
                    <span class="text-[11px] text-[#9CA6BA]">Temporarily suspended</span>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-xs font-medium text-[#737D90] uppercase tracking-wider block mb-1">Archived Methods</span>
                    <p class="text-2xl font-bold text-white">{archived_pms}</p>
                    <span class="text-[11px] text-[#9CA6BA]">Decommissioned</span>
                </div>
            </div>

            <!-- Table -->
            <div class="rounded-2xl bg-[#171A21] border border-[#292E38] overflow-hidden">
                <div class="p-4 border-b border-[#292E38] flex items-center justify-between">
                    <h3 class="font-semibold text-white text-sm">Configured Deposit Assets</h3>
                    <span class="text-xs text-[#737D90]">Changes immediately synchronized with customer app</span>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-sm text-[#9CA6BA]">
                        <thead class="bg-[#12151B] text-[11px] font-semibold uppercase tracking-wider text-[#737D90] border-b border-[#292E38]">
                            <tr>
                                <th class="px-4 py-3">Asset & Method</th>
                                <th class="px-4 py-3">Network</th>
                                <th class="px-4 py-3">Deposit Wallet Address</th>
                                <th class="px-4 py-3">Limits (USD)</th>
                                <th class="px-4 py-3">Confirmations / Fee</th>
                                <th class="px-4 py-3">Status</th>
                                <th class="px-4 py-3 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#292E38]">
                            {pm_rows}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Enhanced Add Payment Method Modal -->
        <div id="addMethodModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm overflow-y-auto">
            <div class="w-full max-w-2xl bg-[#171A21] border border-[#292E38] rounded-2xl p-6 shadow-2xl relative my-8 max-h-[90vh] overflow-y-auto">
                <button onclick="document.getElementById('addMethodModal').classList.add('hidden')" class="absolute top-5 right-5 text-[#737D90] hover:text-white z-10"><i class="fa-solid fa-xmark text-lg"></i></button>
                <h3 class="text-lg font-bold text-white mb-1">Add Payment Method</h3>
                <p class="text-xs text-[#9CA6BA] mb-5">Configure a new deposit method with asset, network, wallet address, icon, QR code, and limits.</p>
                <form method="POST" action="/admin/payment-methods" class="space-y-4" enctype="multipart/form-data">
                    <div>
                        <label class="block text-xs text-[#9CA6BA] mb-1">Payment Type *</label>
                        <select name="payment_type" id="add_payment_type" onchange="toggleCryptoFields(this.value,'add')" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white">
                            <option value="cryptocurrency" selected>Cryptocurrency</option>
                            <option value="bank_transfer">Bank Transfer</option>
                        </select>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Asset Code *</label><input type="text" name="code" placeholder="USDC, BTC, ETH" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div id="add_network_field"><label class="block text-xs text-[#9CA6BA] mb-1">Network Code *</label><input type="text" name="network" placeholder="SOL, ERC20, TRC20" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Method Name *</label><input type="text" name="name" placeholder="USD Coin (Solana)" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Destination Wallet Address *</label><input type="text" name="wallet_address" placeholder="7Xaw... or 0x..." required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 font-mono text-sm text-white"></div>

                    <!-- Icon Upload Section -->
                    <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] space-y-3">
                        <label class="block text-xs font-semibold text-white"><i class="fa-solid fa-image mr-1.5 text-[#246BFD]"></i>Payment Method Icon</label>
                        <div class="flex items-center gap-4">
                            <div id="add_icon_preview" class="w-14 h-14 rounded-xl bg-[#20242D] border border-[#292E38] flex items-center justify-center overflow-hidden">
                                <i class="fa-solid fa-coins text-[#737D90] text-xl"></i>
                            </div>
                            <div class="flex-1">
                                <input type="file" name="icon_file" id="add_icon_file" accept="image/png,image/jpeg,image/webp,image/svg+xml" class="hidden" onchange="previewIcon(this,'add_icon_preview')">
                                <button type="button" onclick="document.getElementById('add_icon_file').click()" class="px-3 py-1.5 rounded-lg bg-[#20242D] border border-[#292E38] text-xs text-white hover:bg-[#252A35]"><i class="fa-solid fa-upload mr-1"></i>Upload Icon</button>
                                <button type="button" onclick="clearIcon('add_icon_file','add_icon_preview')" class="px-3 py-1.5 rounded-lg text-xs text-[#737D90] hover:text-red-400 ml-1"><i class="fa-solid fa-trash-can mr-1"></i>Remove</button>
                                <p class="text-[10px] text-[#737D90] mt-1">PNG, JPG, WebP, SVG. Max 2MB.</p>
                            </div>
                        </div>
                    </div>

                    <!-- QR Code Section -->
                    <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] space-y-3" id="add_qr_section">
                        <label class="block text-xs font-semibold text-white"><i class="fa-solid fa-qrcode mr-1.5 text-[#246BFD]"></i>QR Code Configuration</label>
                        <div class="flex gap-3">
                            <label class="flex items-center gap-2 cursor-pointer"><input type="radio" name="qr_type" value="auto" class="accent-[#246BFD]" checked onchange="toggleQrSection(this.value,'add')"><span class="text-xs text-[#9CA6BA]">Auto-generate from address</span></label>
                            <label class="flex items-center gap-2 cursor-pointer"><input type="radio" name="qr_type" value="upload" class="accent-[#246BFD]" onchange="toggleQrSection(this.value,'add')"><span class="text-xs text-[#9CA6BA]">Upload QR image</span></label>
                            <label class="flex items-center gap-2 cursor-pointer"><input type="radio" name="qr_type" value="none" class="accent-[#246BFD]" onchange="toggleQrSection(this.value,'add')"><span class="text-xs text-[#9CA6BA]">None</span></label>
                        </div>
                        <div id="add_qr_preview" class="flex items-center justify-center p-3 rounded-lg bg-white" style="display:none;">
                            <canvas id="add_qr_canvas" width="180" height="180"></canvas>
                        </div>
                        <div id="add_qr_upload_area" class="hidden">
                            <input type="file" name="qr_file" accept="image/png,image/jpeg,image/webp" class="w-full bg-[#171A21] border border-dashed border-[#292E38] rounded-xl px-3 py-3 text-xs text-[#9CA6BA]">
                        </div>
                        <input type="hidden" name="qr_enabled" value="1">
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Min Deposit ($)</label><input type="number" step="0.01" name="min_deposit" value="50.00" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Max Deposit ($)</label><input type="number" step="1" name="max_deposit" value="100000.00" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div class="grid grid-cols-3 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Fee (%)</label><input type="number" step="0.01" name="processing_fee_pct" value="0.00" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Confirmations</label><input type="number" name="required_confirmations" value="12" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Processing Time</label><input type="text" name="processing_time" value="3 - 8 mins" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">User-Facing Instructions</label><textarea name="instructions" rows="2" placeholder="Send only USDC via Solana network..." class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white resize-none"></textarea></div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs text-[#9CA6BA] mb-1">Status</label>
                            <select name="status" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white">
                                <option value="active" selected>Active</option>
                                <option value="disabled">Disabled</option>
                            </select>
                        </div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Sort Order</label><input type="number" name="sort_order" value="{total_pms + 1}" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Internal Admin Notes</label><textarea name="notes" rows="2" placeholder="Private notes visible only to administrators..." class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-[#9CA6BA] resize-none"></textarea></div>
                    <div class="flex justify-end gap-2 pt-2 border-t border-[#292E38]">
                        <button type="button" onclick="document.getElementById('addMethodModal').classList.add('hidden')" class="px-4 py-2.5 rounded-xl text-xs text-[#9CA6BA] hover:text-white">Cancel</button>
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-bold shadow-lg shadow-blue-500/20"><i class="fa-solid fa-plus mr-1"></i>Create Method</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Edit Payment Method Modal -->
        <div id="editMethodModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm overflow-y-auto">
            <div class="w-full max-w-2xl bg-[#171A21] border border-[#292E38] rounded-2xl p-6 shadow-2xl relative my-8 max-h-[90vh] overflow-y-auto">
                <button onclick="document.getElementById('editMethodModal').classList.add('hidden')" class="absolute top-5 right-5 text-[#737D90] hover:text-white z-10"><i class="fa-solid fa-xmark text-lg"></i></button>
                <h3 class="text-lg font-bold text-white mb-1"><i class="fa-solid fa-pen-to-square mr-2 text-[#246BFD]"></i>Edit Payment Method</h3>
                <p class="text-xs text-[#9CA6BA] mb-5">Update configuration. Wallet address changes are logged in the audit trail.</p>
                <form method="POST" id="editMethodForm" action="/admin/payment-methods/1/update" class="space-y-4" enctype="multipart/form-data">
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Asset Code *</label><input type="text" name="code" id="edit_code" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Network Code *</label><input type="text" name="network" id="edit_network" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Method Name *</label><input type="text" name="name" id="edit_name" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    <div>
                        <label class="block text-xs text-[#9CA6BA] mb-1">Wallet Address *</label>
                        <input type="text" name="wallet_address" id="edit_wallet" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 font-mono text-sm text-white">
                        <p class="text-[10px] text-amber-400 mt-1"><i class="fa-solid fa-triangle-exclamation mr-1"></i>Changing the wallet address will be logged in the audit trail. Historical deposits retain their original address.</p>
                    </div>

                    <!-- Icon Preview/Upload for Edit -->
                    <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] space-y-3">
                        <label class="block text-xs font-semibold text-white"><i class="fa-solid fa-image mr-1.5 text-[#246BFD]"></i>Icon</label>
                        <div class="flex items-center gap-4">
                            <div id="edit_icon_preview" class="w-14 h-14 rounded-xl bg-[#20242D] border border-[#292E38] flex items-center justify-center overflow-hidden">
                                <i class="fa-solid fa-coins text-[#737D90] text-xl"></i>
                            </div>
                            <div>
                                <input type="file" name="icon_file" id="edit_icon_file" accept="image/png,image/jpeg,image/webp,image/svg+xml" class="hidden" onchange="previewIcon(this,'edit_icon_preview')">
                                <button type="button" onclick="document.getElementById('edit_icon_file').click()" class="px-3 py-1.5 rounded-lg bg-[#20242D] border border-[#292E38] text-xs text-white hover:bg-[#252A35]"><i class="fa-solid fa-upload mr-1"></i>Replace Icon</button>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Min Deposit ($)</label><input type="number" step="0.01" name="min_deposit" id="edit_min" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Max Deposit ($)</label><input type="number" step="1" name="max_deposit" id="edit_max" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div class="grid grid-cols-3 gap-3">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Fee (%)</label><input type="number" step="0.01" name="processing_fee_pct" id="edit_fee" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Confirmations</label><input type="number" name="required_confirmations" id="edit_confirms" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Processing Time</label><input type="text" name="processing_time" id="edit_processing_time" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">User-Facing Instructions</label><textarea name="instructions" id="edit_instructions" rows="2" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white resize-none"></textarea></div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs text-[#9CA6BA] mb-1">Status</label>
                            <select name="status" id="edit_status" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white">
                                <option value="active">Active</option>
                                <option value="disabled">Disabled</option>
                            </select>
                        </div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Sort Order</label><input type="number" name="sort_order" id="edit_sort" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Internal Admin Notes</label><textarea name="notes" id="edit_notes" rows="2" placeholder="Private notes..." class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-[#9CA6BA] resize-none"></textarea></div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Change Reason (for audit trail)</label><input type="text" name="change_reason" value="Administrative configuration update" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></div>
                    <div class="flex justify-end gap-2 pt-2 border-t border-[#292E38]">
                        <button type="button" onclick="document.getElementById('editMethodModal').classList.add('hidden')" class="px-4 py-2.5 rounded-xl text-xs text-[#9CA6BA] hover:text-white">Cancel</button>
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-bold shadow-lg shadow-blue-500/20"><i class="fa-solid fa-save mr-1"></i>Save Changes</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- JavaScript: Edit modal, icon preview, QR generation -->
        <script>
        function openEditModal(pm) {{
            document.getElementById('editMethodForm').action = '/admin/payment-methods/' + pm.id + '/update';
            document.getElementById('edit_name').value = pm.name || '';
            document.getElementById('edit_code').value = pm.code || pm.ticker || '';
            document.getElementById('edit_network').value = pm.network || pm.network_id || '';
            document.getElementById('edit_wallet').value = pm.wallet_address || '';
            document.getElementById('edit_min').value = pm.min_deposit !== undefined ? pm.min_deposit : 50;
            document.getElementById('edit_max').value = pm.max_deposit !== undefined ? pm.max_deposit : 100000;
            document.getElementById('edit_confirms').value = pm.required_confirmations !== undefined ? pm.required_confirmations : 12;
            document.getElementById('edit_fee').value = pm.processing_fee_pct !== undefined ? pm.processing_fee_pct : (pm.deposit_fee_percentage || 0);
            document.getElementById('edit_instructions').value = pm.instructions || '';
            document.getElementById('edit_status').value = pm.status || 'active';
            document.getElementById('edit_sort').value = pm.sort_order || 1;
            document.getElementById('edit_notes').value = pm.notes || '';
            document.getElementById('edit_processing_time').value = pm.processing_time || '3 - 8 mins';
            var prev = document.getElementById('edit_icon_preview');
            var iconUrl = pm.icon_url || (pm.icon_data ? pm.icon_data : '');
            if (iconUrl) {{
                prev.innerHTML = '<img src="' + iconUrl + '" class="w-full h-full object-contain p-1" onerror="this.parentElement.innerHTML=\\'<i class=\\\\'fa-solid fa-coins text-[#737D90] text-xl\\\\'></i>\\'">';
            }} else {{
                prev.innerHTML = '<i class="fa-solid fa-coins text-[#737D90] text-xl"></i>';
            }}
            document.getElementById('editMethodModal').classList.remove('hidden');
        }}

        function previewIcon(input, previewId) {{
            var prev = document.getElementById(previewId);
            if (input.files && input.files[0]) {{
                var maxSize = 2 * 1024 * 1024;
                if (input.files[0].size > maxSize) {{
                    alert('File is too large. Maximum size is 2MB.');
                    input.value = '';
                    return;
                }}
                var reader = new FileReader();
                reader.onload = function(e) {{
                    prev.innerHTML = '<img src="' + e.target.result + '" class="w-full h-full object-contain p-1">';
                }};
                reader.readAsDataURL(input.files[0]);
            }}
        }}

        function clearIcon(inputId, previewId) {{
            document.getElementById(inputId).value = '';
            document.getElementById(previewId).innerHTML = '<i class="fa-solid fa-coins text-[#737D90] text-xl"></i>';
        }}

        function toggleCryptoFields(type, prefix) {{
            var netField = document.getElementById(prefix + '_network_field');
            var qrSection = document.getElementById(prefix + '_qr_section');
            if (type === 'bank_transfer') {{
                if(netField) netField.style.display = 'none';
                if(qrSection) qrSection.style.display = 'none';
            }} else {{
                if(netField) netField.style.display = '';
                if(qrSection) qrSection.style.display = '';
            }}
        }}

        function toggleQrSection(type, prefix) {{
            var preview = document.getElementById(prefix + '_qr_preview');
            var upload = document.getElementById(prefix + '_qr_upload_area');
            if (type === 'auto') {{
                if(preview) preview.style.display = 'flex';
                if(upload) upload.classList.add('hidden');
                generateQrPreview(prefix);
            }} else if (type === 'upload') {{
                if(preview) preview.style.display = 'none';
                if(upload) upload.classList.remove('hidden');
            }} else {{
                if(preview) preview.style.display = 'none';
                if(upload) upload.classList.add('hidden');
            }}
        }}

        function generateQrPreview(prefix) {{
            // Simple QR code generation using canvas (basic version for demo)
            var canvas = document.getElementById(prefix + '_qr_canvas');
            if (!canvas) return;
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = '#FFFFFF';
            ctx.fillRect(0, 0, 180, 180);
            ctx.fillStyle = '#000000';
            ctx.font = '11px monospace';
            ctx.textAlign = 'center';
            ctx.fillText('QR Code will be', 90, 80);
            ctx.fillText('generated from', 90, 95);
            ctx.fillText('wallet address', 90, 110);
            var preview = document.getElementById(prefix + '_qr_preview');
            if(preview) preview.style.display = 'flex';
        }}
        </script>'''
        html = build_admin_layout(body, "Payment Methods & Wallets | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 3. User Management Index
    if path == "/admin/users":
        users_list = STATE.get("users", [])
        total_users = len(users_list)
        active_users = sum(1 for u in users_list if u.get("status") == "active")
        suspended_users = sum(1 for u in users_list if u.get("status") == "suspended")
        email_verified_users = sum(1 for u in users_list if u.get("email_verified_at") is not None)
        email_pending_users = sum(1 for u in users_list if u.get("email_verified_at") is None)
        kyc_approved_users = sum(1 for u in users_list if u.get("kyc_status") == "approved")
        kyc_pending_users = sum(1 for u in users_list if u.get("kyc_status") in ["pending_review", "under_review"])
        kyc_rejected_users = sum(1 for u in users_list if u.get("kyc_status") == "rejected")

        qs = urllib.parse.parse_qs(parsed.query)
        search_q = qs.get("search", [""])[0].lower()
        status_f = qs.get("status", [""])[0].lower()
        kyc_f = qs.get("kyc_status", [""])[0].lower()

        filtered_users = []
        for u in users_list:
            if status_f and u.get("status") != status_f:
                continue
            if kyc_f and u.get("kyc_status") != kyc_f:
                continue
            if search_q:
                full_name = f"{u.get('first_name', '')} {u.get('last_name', '')}".lower()
                email = u.get("email", "").lower()
                uid_str = str(u.get("id", ""))
                if search_q not in full_name and search_q not in email and search_q not in uid_str:
                    continue
            filtered_users.append(u)

        user_rows = ""
        for u in filtered_users:
            bal = STATE["accounts"][0]["balance"] if u["id"] == STATE["user"]["id"] else 0.00
            st = u.get("status", "active")
            st_badge = '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><span class="w-1.5 h-1.5 rounded-full bg-[#20C997]"></span>Active</span>' if st == "active" else '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-[#F05D6C]/10 text-[#F05D6C] border border-[#F05D6C]/20"><i class="fa-solid fa-ban text-[10px]"></i>Suspended</span>'
            em_badge = '<span class="inline-flex items-center gap-1 text-xs text-[#20C997]"><i class="fa-solid fa-circle-check text-[11px]"></i>Verified</span>' if u.get("email_verified_at") else '<span class="inline-flex items-center gap-1 text-xs text-[#F5B942]"><i class="fa-regular fa-clock text-[11px]"></i>Pending</span>'
            kyc = u.get("kyc_status", "unverified")
            if kyc == "approved":
                kyc_badge = '<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><i class="fa-solid fa-shield-check text-[10px]"></i>Approved</span>'
            elif kyc in ["pending_review", "under_review"]:
                kyc_badge = '<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-[#8054F6]/10 text-[#8054F6] border border-[#8054F6]/20"><i class="fa-solid fa-hourglass-half text-[10px]"></i>Pending</span>'
            elif kyc == "rejected":
                kyc_badge = '<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-[#F05D6C]/10 text-[#F05D6C] border border-[#F05D6C]/20"><i class="fa-solid fa-triangle-exclamation text-[10px]"></i>Rejected</span>'
            else:
                kyc_badge = '<span class="inline-flex items-center gap-1 text-xs text-[#737D90]">Unverified</span>'

            user_rows += f"""
            <tr class="hover:bg-[#1C202A] transition-colors">
                <td class="px-4 py-3.5">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-full bg-gradient-to-tr from-[#246BFD] to-[#8054F6] flex items-center justify-center text-xs font-bold text-white shadow">
                            {u['first_name'][0]}{u['last_name'][0]}
                        </div>
                        <div>
                            <a href="/admin/users/{u['id']}" class="font-semibold text-white hover:text-[#246BFD] transition-colors">{u['first_name']} {u['last_name']}</a>
                            <p class="text-xs text-[#737D90]">{u['email']} • ID #{u['id']}</p>
                        </div>
                    </div>
                </td>
                <td class="px-4 py-3.5 font-mono font-bold text-white">${bal:,.2f}</td>
                <td class="px-4 py-3.5">{st_badge}</td>
                <td class="px-4 py-3.5">{em_badge}</td>
                <td class="px-4 py-3.5">{kyc_badge}</td>
                <td class="px-4 py-3.5 text-xs text-[#737D90]">{u.get('created_at', '2026-10-20')[:10]}</td>
                <td class="px-4 py-3.5 text-right">
                    <div class="inline-flex items-center gap-2">
                        <a href="/admin/users/{u['id']}" class="px-3 py-1.5 rounded-lg bg-[#20242D] hover:bg-[#246BFD] hover:text-white text-white text-xs font-semibold transition-all">Manage</a>
                        <form method="POST" action="/admin/impersonate/{u['id']}" class="inline" onsubmit="return confirm('Launch support session to impersonate {u['first_name']} {u['last_name']}?');">
                            <button type="submit" class="p-1.5 rounded-lg bg-amber-500/10 hover:bg-amber-500/20 text-[#F5B942] text-xs transition-colors" title="Login as User (Support Session)">
                                <i class="fa-solid fa-user-secret"></i>
                            </button>
                        </form>
                    </div>
                </td>
            </tr>"""

        body = f'''<div class="space-y-6">
            <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-[#737D90] mb-1">
                        <a href="/admin" class="hover:text-white transition-colors">Admin</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <span class="text-white">Customer Accounts</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Customer Accounts & User Management</h1>
                    <p class="text-xs text-[#9CA6BA] mt-0.5">Oversee customer accounts, enforce compliance, verify emails, review KYC, and perform support sessions.</p>
                </div>
                <div>
                    <span class="px-3 py-1.5 rounded-xl bg-[#171A21] border border-[#292E38] text-xs font-semibold text-white">Total: {total_users} Users</span>
                </div>
            </div>

            <!-- 8 KPI Summary Cards -->
            <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#737D90] block mb-1">Total Users</span>
                    <p class="text-xl font-bold text-white">{total_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Registered</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#20C997] block mb-1">Active</span>
                    <p class="text-xl font-bold text-[#20C997]">{active_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Operational</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#F05D6C] block mb-1">Suspended</span>
                    <p class="text-xl font-bold text-[#F05D6C]">{suspended_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Blocked</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#20C997] block mb-1">Email Verified</span>
                    <p class="text-xl font-bold text-white">{email_verified_users}</p>
                    <span class="text-[10px] text-[#20C997]">Confirmed</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#F5B942] block mb-1">Email Pending</span>
                    <p class="text-xl font-bold text-[#F5B942]">{email_pending_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Unverified</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#20C997] block mb-1">KYC Approved</span>
                    <p class="text-xl font-bold text-[#20C997]">{kyc_approved_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Verified Tier</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#8054F6] block mb-1">KYC Review</span>
                    <p class="text-xl font-bold text-[#8054F6]">{kyc_pending_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Needs Review</span>
                </div>
                <div class="p-3.5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-[10px] font-semibold uppercase text-[#737D90] block mb-1">KYC Rejected</span>
                    <p class="text-xl font-bold text-white">{kyc_rejected_users}</p>
                    <span class="text-[10px] text-[#9CA6BA]">Requires Docs</span>
                </div>
            </div>

            <!-- Search & Filter Toolbar -->
            <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                <form method="GET" action="/admin/users" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
                    <div class="relative lg:col-span-2">
                        <i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-xs text-[#737D90]"></i>
                        <input type="text" name="search" value="{search_q}" placeholder="Search by name, email, or user ID..." class="w-full bg-[#12151B] border border-[#292E38] rounded-xl pl-9 pr-4 py-2 text-sm text-white placeholder-[#737D90] focus:outline-none focus:border-[#246BFD]">
                    </div>
                    <div>
                        <select name="status" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-[#246BFD]">
                            <option value="">All Account Statuses</option>
                            <option value="active" {"selected" if status_f == "active" else ""}>Active Only</option>
                            <option value="suspended" {"selected" if status_f == "suspended" else ""}>Suspended Only</option>
                        </select>
                    </div>
                    <div>
                        <select name="kyc_status" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-[#246BFD]">
                            <option value="">All KYC Statuses</option>
                            <option value="approved" {"selected" if kyc_f == "approved" else ""}>Approved</option>
                            <option value="pending_review" {"selected" if kyc_f == "pending_review" else ""}>Pending Review</option>
                            <option value="rejected" {"selected" if kyc_f == "rejected" else ""}>Rejected</option>
                        </select>
                    </div>
                    <div class="flex items-center gap-2">
                        <button type="submit" class="flex-1 px-4 py-2 rounded-xl bg-[#20242D] hover:bg-[#292E38] text-white text-sm font-medium transition-colors">Apply</button>
                        <a href="/admin/users" class="px-3 py-2 rounded-xl bg-transparent hover:bg-[#20242D] text-[#9CA6BA] hover:text-white text-sm font-medium transition-colors">Reset</a>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="rounded-2xl bg-[#171A21] border border-[#292E38] overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-sm text-[#9CA6BA]">
                        <thead class="bg-[#12151B] text-[11px] font-semibold uppercase tracking-wider text-[#737D90] border-b border-[#292E38]">
                            <tr>
                                <th class="px-4 py-3">Customer Profile</th>
                                <th class="px-4 py-3">USD Balance</th>
                                <th class="px-4 py-3">Account Status</th>
                                <th class="px-4 py-3">Email Verification</th>
                                <th class="px-4 py-3">KYC Status</th>
                                <th class="px-4 py-3">Joined Date</th>
                                <th class="px-4 py-3 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#292E38]">
                            {user_rows}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>'''
        html = build_admin_layout(body, "Customer Accounts | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 4. User Profile Show View
    if path.startswith("/admin/users/"):
        uid = int(path.split("/")[3])
        u = next((x for x in STATE.get("users", []) if x["id"] == uid), STATE["user"])
        qs = urllib.parse.parse_qs(parsed.query)
        tab = qs.get("tab", ["profile"])[0]

        bal = STATE["accounts"][0]["balance"] if u["id"] == STATE["user"]["id"] else 0.00
        st = u.get("status", "active")
        st_badge = '<span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><span class="w-1.5 h-1.5 rounded-full bg-[#20C997] animate-pulse"></span>Active</span>' if st == "active" else '<span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-[#F05D6C]/10 text-[#F05D6C] border border-[#F05D6C]/20"><i class="fa-solid fa-ban text-[10px]"></i>Suspended</span>'
        em_badge = f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><i class="fa-solid fa-check text-[10px]"></i> Verified</span>' if u.get("email_verified_at") else f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-[#F5B942]/10 text-[#F5B942] border border-[#F5B942]/20"><i class="fa-regular fa-clock text-[10px]"></i> Email Pending</span>'
        kyc = u.get("kyc_status", "unverified")
        kyc_badge = f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20"><i class="fa-solid fa-shield-check text-[10px]"></i> KYC {kyc.capitalize()}</span>'

        tab_links = ""
        all_tabs = [
            ('profile', 'Profile Details', 'fa-user'),
            ('status', 'Account Status', 'fa-shield-halved'),
            ('email', 'Email Verification', 'fa-envelope-circle-check'),
            ('kyc', 'KYC Compliance', 'fa-id-card'),
            ('balance', 'Balance & Ledger', 'fa-wallet'),
            ('activity', 'Transfers & Deposits', 'fa-clock-rotate-left'),
            ('cards', 'Payment Cards', 'fa-credit-card'),
            ('audit', 'Audit & Security', 'fa-file-shield'),
        ]
        for tkey, tlabel, ticon in all_tabs:
            tactive = (tab == tkey)
            tcls = 'border-[#246BFD] text-[#246BFD] bg-[#246BFD]/5 font-semibold' if tactive else 'border-transparent text-[#9CA6BA] hover:text-white'
            tab_links += f'<a href="?tab={tkey}" class="inline-flex items-center gap-2 px-4 py-3 border-b-2 text-xs transition-colors whitespace-nowrap {tcls}"><i class="fa-solid {ticon}"></i><span>{tlabel}</span></a>'

        tab_body = ""
        if tab == "profile":
            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-3xl">
                <h3 class="text-base font-bold text-white mb-1">Edit Customer Profile</h3>
                <p class="text-xs text-[#9CA6BA] mb-6">Update contact details and address information.</p>
                <form method="POST" action="/admin/users/{u['id']}/update-profile" class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">First Name *</label><input type="text" name="first_name" value="{u['first_name']}" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Last Name *</label><input type="text" name="last_name" value="{u['last_name']}" required class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Email</label><input type="email" value="{u['email']}" disabled class="w-full bg-[#0E1015] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-[#737D90]"></div>
                        <div><label class="block text-xs text-[#9CA6BA] mb-1">Phone</label><input type="text" name="phone" value="{u.get('phone', '')}" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white"></div>
                    </div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Country</label><input type="text" name="country" value="{u.get('country', '')}" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white"></div>
                    <div><label class="block text-xs text-[#9CA6BA] mb-1">Physical Address</label><textarea name="address" rows="2" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white">{u.get('address', '')}</textarea></div>
                    <div class="pt-4 border-t border-[#292E38] flex justify-end">
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-sm font-semibold">Save Profile Changes</button>
                    </div>
                </form>
            </div>'''

        elif tab == "status":
            action_btn = f'''
            <form method="POST" action="/admin/users/{u['id']}/toggle-status" class="space-y-4">
                <div>
                    <label class="block text-xs font-medium text-[#F05D6C] mb-1.5">Suspension Reason * (Recorded in audit log)</label>
                    <textarea name="suspend_reason" rows="3" required placeholder="Specify reason..." class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3.5 py-2 text-sm text-white"></textarea>
                </div>
                <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#F05D6C] hover:bg-red-600 text-white text-xs font-bold">Suspend Customer Account</button>
            </form>''' if u['status'] == "active" else f'''
            <form method="POST" action="/admin/users/{u['id']}/toggle-status">
                <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#20C997] hover:bg-emerald-600 text-white text-xs font-bold">Reinstate Account</button>
            </form>'''

            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-3xl space-y-4">
                <h3 class="text-base font-bold text-white">Account Status: {u['status'].upper()}</h3>
                <p class="text-xs text-[#9CA6BA]">Suspended accounts are strictly blocked from initiating deposits, sending transfers, or issuing cards.</p>
                {action_btn}
            </div>'''

        elif tab == "email":
            action_form = f'''
            <form method="POST" action="/admin/users/{u['id']}/verify-email">
                <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#20C997] hover:bg-emerald-600 text-white text-xs font-bold">Mark Email as Verified</button>
            </form>''' if not u.get("email_verified_at") else f'''
            <form method="POST" action="/admin/users/{u['id']}/revoke-email">
                <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#F05D6C]/10 text-[#F05D6C] border border-[#F05D6C]/30 text-xs font-bold">Revoke Email Verification</button>
            </form>'''

            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-3xl space-y-4">
                <h3 class="text-base font-bold text-white">Email Verification</h3>
                <p class="text-xs text-[#9CA6BA]">Current status: {("Verified on " + u['email_verified_at']) if u.get("email_verified_at") else "Pending Verification"}</p>
                {action_form}
            </div>'''

        elif tab == "kyc":
            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-3xl space-y-4">
                <h3 class="text-base font-bold text-white">KYC Verification Tier: {u.get("kyc_status", "unverified").upper()}</h3>
                <p class="text-xs text-[#9CA6BA]">Document Type: {u.get("kyc_document_type", "Passport")}</p>
                <div class="flex items-center gap-3 pt-2">
                    <form method="POST" action="/admin/users/{u['id']}/kyc">
                        <input type="hidden" name="action" value="approve">
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#20C997] hover:bg-emerald-600 text-white text-xs font-bold">Approve KYC Verification</button>
                    </form>
                    <form method="POST" action="/admin/users/{u['id']}/kyc">
                        <input type="hidden" name="action" value="reject">
                        <input type="hidden" name="reason" value="Identity verification documents could not be validated.">
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#F05D6C]/10 text-[#F05D6C] border border-[#F05D6C]/30 text-xs font-bold">Reject KYC</button>
                    </form>
                </div>
            </div>'''

        elif tab == "balance":
            tab_body = f'''
            <div class="space-y-4 max-w-3xl">
                <div class="flex items-center justify-between">
                    <h3 class="text-base font-bold text-white">Account Balances & Double-Entry Ledger</h3>
                    <button onclick="document.getElementById('adjustBalanceModal').classList.remove('hidden')" class="px-4 py-2 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-bold">Adjust Balance</button>
                </div>
                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <span class="text-xs text-[#737D90]">Primary Checking (USD)</span>
                    <p class="text-2xl font-mono font-bold text-white mt-1">${bal:,.2f} USD</p>
                    <span class="text-[11px] text-[#20C997]"><i class="fa-solid fa-check mr-1"></i> Authoritative Double-Entry Ledger Synchronized</span>
                </div>
            </div>'''

        elif tab == "activity":
            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-4xl">
                <h3 class="text-base font-bold text-white mb-3">Transaction Activity</h3>
                <p class="text-xs text-[#9CA6BA]">Total transactions recorded: {len(STATE.get("transfers", [])) + len(STATE.get("deposits", []))}</p>
            </div>'''

        elif tab == "cards":
            tab_body = f'''
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] max-w-3xl">
                <h3 class="text-base font-bold text-white mb-3">Issued Payment Cards</h3>
                <p class="text-xs text-[#9CA6BA]">Customer currently has {len(STATE.get("cards", []))} payment cards.</p>
            </div>'''

        elif tab == "audit":
            logs = [l for l in STATE.get("audit_logs", []) if str(u['id']) in str(l.get("details", ""))]
            log_rows = "".join([f'<tr class="hover:bg-[#1C202A]"><td class="px-4 py-2 text-white font-mono">{l["action"]}</td><td class="px-4 py-2 text-[#9CA6BA]">{l.get("details", "")}</td><td class="px-4 py-2 text-[#737D90]">{l.get("created_at", "")}</td></tr>' for l in logs]) if logs else '<tr><td colspan="3" class="px-4 py-6 text-center text-[#737D90]">No audit logs for this user.</td></tr>'
            tab_body = f'''
            <div class="rounded-2xl bg-[#171A21] border border-[#292E38] overflow-hidden max-w-4xl">
                <div class="p-4 border-b border-[#292E38]"><h3 class="font-semibold text-white text-sm">Security & Administrative Audit Trail</h3></div>
                <table class="w-full text-left text-xs"><tbody class="divide-y divide-[#292E38]">{log_rows}</tbody></table>
            </div>'''

        body = f'''<div class="space-y-6">
            <div class="flex items-center justify-between">
                <a href="/admin/users" class="inline-flex items-center gap-1.5 text-xs text-[#9CA6BA] hover:text-white transition-colors">
                    <i class="fa-solid fa-arrow-left text-[10px]"></i><span>Back to Customer Directory</span>
                </a>
                <span class="text-xs text-[#737D90]">User ID #{u['id']}</span>
            </div>

            <!-- Header Profile Card -->
            <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
                    <div class="flex items-center gap-4">
                        <div class="w-16 h-16 rounded-2xl bg-gradient-to-tr from-[#246BFD] to-[#8054F6] flex items-center justify-center text-xl font-bold text-white shadow-lg">
                            {u['first_name'][0]}{u['last_name'][0]}
                        </div>
                        <div>
                            <div class="flex items-center gap-2 mb-1">
                                <h1 class="text-2xl font-bold text-white">{u['first_name']} {u['last_name']}</h1>
                                {st_badge}
                                {em_badge}
                                {kyc_badge}
                            </div>
                            <p class="text-xs text-[#9CA6BA]">{u['email']} • {u.get('phone', 'No phone')} • {u.get('country', 'United States')}</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <form method="POST" action="/admin/impersonate/{u['id']}" class="inline">
                            <button type="submit" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 text-slate-950 font-bold text-xs shadow-lg shadow-amber-500/20">
                                <i class="fa-solid fa-user-secret text-sm"></i>
                                <span>Login as User (Support Mode)</span>
                            </button>
                        </form>
                        <button onclick="document.getElementById('adjustBalanceModal').classList.remove('hidden')" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[#246BFD] text-white font-semibold text-xs shadow-lg shadow-blue-500/20">
                            <i class="fa-solid fa-scale-balanced text-sm"></i>
                            <span>Manage Balance</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Tabs -->
            <div class="flex border-b border-[#292E38] overflow-x-auto gap-1">
                {tab_links}
            </div>

            <div>
                {tab_body}
            </div>
        </div>

        <!-- Modal: Adjust Balance -->
        <div id="adjustBalanceModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/75 backdrop-blur-sm">
            <div class="w-full max-w-md bg-[#171A21] border border-[#292E38] rounded-2xl p-6 shadow-2xl relative">
                <button onclick="document.getElementById('adjustBalanceModal').classList.add('hidden')" class="absolute top-5 right-5 text-[#737D90] hover:text-white"><i class="fa-solid fa-xmark text-lg"></i></button>
                <h3 class="text-lg font-bold text-white mb-1">Adjust Customer Balance</h3>
                <p class="text-xs text-[#9CA6BA] mb-4">Atomic double-entry ledger adjustment.</p>
                <form method="POST" action="/admin/users/{u['id']}/adjust-balance" class="space-y-4">
                    <div>
                        <label class="block text-xs text-[#9CA6BA] mb-1">Direction *</label>
                        <select name="direction" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white">
                            <option value="credit">Credit (Increase Balance)</option>
                            <option value="debit">Debit (Decrease Balance)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs text-[#9CA6BA] mb-1">Amount ($ USD) *</label>
                        <input type="number" step="0.01" min="0.01" name="amount" required placeholder="100.00" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white">
                    </div>
                    <div>
                        <label class="block text-xs text-[#9CA6BA] mb-1">Reason / Justification *</label>
                        <textarea name="reason" rows="2" required placeholder="e.g. Account reconciliation" class="w-full bg-[#12151B] border border-[#292E38] rounded-xl px-3 py-2 text-sm text-white"></textarea>
                    </div>
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="allow_overdraft" name="allow_overdraft" value="1">
                        <label for="allow_overdraft" class="text-xs text-[#9CA6BA]">Allow overdraft on debit</label>
                    </div>
                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" onclick="document.getElementById('adjustBalanceModal').classList.add('hidden')" class="px-4 py-2 rounded-xl text-xs text-[#9CA6BA]">Cancel</button>
                        <button type="submit" class="px-5 py-2 rounded-xl bg-[#246BFD] text-white text-xs font-bold">Post Adjustment</button>
                    </div>
                </form>
            </div>
        </div>'''
        html = build_admin_layout(body, f"User: {u['first_name']} {u['last_name']} | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 5. KYC Document Viewer
    if path.startswith("/admin/kyc/document/"):
        doc_id = path.split("/")[4]
        sub = next((k for k in STATE.get("kyc_verifications", []) if str(k["id"]) == doc_id), None)
        doc_type = sub.get("document_type", "Government ID") if sub else "Government ID"
        doc_user = f"{sub.get('first_name', '')} {sub.get('last_name', '')}" if sub else "Customer"
        svg = f'''<svg xmlns="http://www.w3.org/2000/svg" width="600" height="380" viewBox="0 0 600 380">
            <rect width="600" height="380" rx="16" fill="#161A22" stroke="#282E3E" stroke-width="2"/>
            <rect x="30" y="30" width="120" height="150" rx="8" fill="#246BFD" fill-opacity="0.1" stroke="#246BFD" stroke-width="1"/>
            <circle cx="90" cy="85" r="30" fill="#246BFD" fill-opacity="0.3"/>
            <path d="M50 160 C50 130 130 130 130 160 Z" fill="#246BFD" fill-opacity="0.3"/>
            <text x="180" y="65" fill="#FFFFFF" font-family="sans-serif" font-size="20" font-weight="bold">{doc_type}</text>
            <text x="180" y="95" fill="#8F9CAE" font-family="sans-serif" font-size="14">Holder: {doc_user}</text>
            <text x="180" y="125" fill="#8F9CAE" font-family="sans-serif" font-size="14">Document ID: {sub.get("id_number", "VERIFIED-DOC") if sub else "DL-98234-UK"}</text>
            <text x="180" y="155" fill="#10B981" font-family="sans-serif" font-size="12" font-weight="bold">OFFICIAL DIGITAL SECURITY COPY</text>
            <line x1="30" y1="210" x2="570" y2="210" stroke="#282E3E" stroke-width="1"/>
            <text x="30" y="250" fill="#8F9CAE" font-family="monospace" font-size="12">P&lt;USA{sub.get("last_name", "SMITH").upper()}&lt;&lt;{sub.get("first_name", "JOHN").upper()}&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</text>
            <text x="30" y="280" fill="#8F9CAE" font-family="monospace" font-size="12">98234UK5829104M2801014&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;04</text>
            <rect x="30" y="320" width="540" height="30" rx="6" fill="#0B0E14"/>
            <text x="45" y="340" fill="#5C6779" font-family="sans-serif" font-size="11">Alliance Bank Compliance Cryptographic Proof &bull; Confidential Verification Document</text>
        </svg>'''
        handler.send_response(200)
        handler.send_header("Content-Type", "image/svg+xml")
        handler.end_headers()
        handler.wfile.write(svg.encode('utf-8'))
        return True

    # 6. KYC Compliance Management Index
    if path == "/admin/kyc":
        subs = STATE.get("kyc_verifications", [])
        total_sub = len(subs)
        pending = sum(1 for s in subs if s.get("status") == "pending_review")
        under_review = sum(1 for s in subs if s.get("status") == "under_review")
        approved = sum(1 for s in subs if s.get("status") == "approved")
        rejected = sum(1 for s in subs if s.get("status") == "rejected")
        add_info = sum(1 for s in subs if s.get("status") == "additional_info_required")

        qs = urllib.parse.parse_qs(parsed.query)
        search_q = qs.get("search", [""])[0].lower().strip()
        status_filter = qs.get("status", [""])[0].strip()
        doc_filter = qs.get("document_type", [""])[0].strip()

        filtered_subs = subs
        if status_filter:
            filtered_subs = [s for s in filtered_subs if s.get("status") == status_filter]
        if doc_filter:
            filtered_subs = [s for s in filtered_subs if s.get("document_type") == doc_filter]
        if search_q:
            filtered_subs = [s for s in filtered_subs if (
                search_q in s.get("first_name", "").lower() or
                search_q in s.get("last_name", "").lower() or
                search_q in s.get("email", "").lower() or
                search_q in s.get("account_number", "").lower() or
                search_q in str(s.get("user_id", "")).lower()
            )]

        rows_html = ""
        for s in filtered_subs:
            st = s.get("status", "pending_review")
            badge_class = {
                "approved": "bg-[#20C997]/10 text-[#20C997] border-[#20C997]/20",
                "pending_review": "bg-[#F5B942]/10 text-[#F5B942] border-[#F5B942]/20",
                "under_review": "bg-[#246BFD]/10 text-[#246BFD] border-[#246BFD]/20",
                "rejected": "bg-[#F05D6C]/10 text-[#F05D6C] border-[#F05D6C]/20",
                "additional_info_required": "bg-orange-500/10 text-orange-400 border-orange-500/20"
            }.get(st, "bg-white/10 text-[#8F9CAE] border-white/10")

            badge_label = {
                "approved": "Approved",
                "pending_review": "Pending Review",
                "under_review": "Under Review",
                "rejected": "Rejected",
                "additional_info_required": "Info Required"
            }.get(st, st.capitalize())

            s_json = json.dumps(s).replace("'", "&#39;")
            rows_html += f'''
            <tr class="hover:bg-white/[0.02] transition-colors">
                <td class="py-3.5 px-4">
                    <div class="font-semibold text-white">{s.get("first_name", "")} {s.get("last_name", "")}</div>
                    <div class="text-[11px] text-[#8F9CAE]">{s.get("email", "")} &bull; ID #{s.get("user_id", "")}</div>
                </td>
                <td class="py-3.5 px-4 font-mono font-medium text-gray-300">
                    {s.get("account_number", "—")}
                </td>
                <td class="py-3.5 px-4">
                    <div class="font-medium text-white">{s.get("document_type", "ID")}</div>
                    <div class="text-[11px] text-[#8F9CAE] font-mono">{s.get("id_number", "—")}</div>
                </td>
                <td class="py-3.5 px-4 text-[#C2C9D6]">
                    {s.get("submitted_at", "Just now")}
                </td>
                <td class="py-3.5 px-4">
                    <span class="inline-flex items-center px-2.5 py-1 rounded-full text-[11px] font-semibold border {badge_class}">
                        {badge_label}
                    </span>
                </td>
                <td class="py-3.5 px-4 text-[#8F9CAE] text-[11px]">
                    {s.get("updated_at", "—")}
                </td>
                <td class="py-3.5 px-4 text-right">
                    <button type="button" onclick='openReviewModal({s_json})' class="px-3 py-1.5 rounded-lg text-xs font-semibold bg-[#246BFD]/10 hover:bg-[#246BFD]/20 text-[#246BFD] border border-[#246BFD]/30 transition-all">
                        Review Submission
                    </button>
                </td>
            </tr>'''

        if not rows_html:
            rows_html = '''<tr><td colspan="7" class="py-12 text-center text-[#8F9CAE]">
                <div class="font-semibold text-white">No KYC Submissions Found</div>
                <div class="text-[11px] mt-1">There are no verification documents matching your criteria.</div>
            </td></tr>'''

        body = f'''<div class="space-y-6">
            <!-- Header -->
            <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 & Regulatory</span>
                        <span>&bull;</span>
                        <span>Tier 2 Verification</span>
                    </div>
                    <h1 class="text-2xl sm:text-3xl font-extrabold text-white tracking-tight">KYC Compliance Management</h1>
                    <p class="text-xs sm:text-sm text-[#8F9CAE] mt-0.5">Authoritative identity verification queue, document inspection, and review decisions.</p>
                </div>
            </div>

            <!-- KPI Cards -->
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4">
                <div class="bg-[#161A22] border border-[#282E3E] rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-[#8F9CAE]">Total Submissions</div>
                    <div class="text-xl sm:text-2xl font-bold text-white mt-1.5">{total_sub}</div>
                </div>
                <div class="bg-[#161A22] border border-amber-500/30 rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-amber-400">Pending Review</div>
                    <div class="text-xl sm:text-2xl font-bold text-amber-400 mt-1.5">{pending}</div>
                </div>
                <div class="bg-[#161A22] border border-blue-500/30 rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-blue-400">Under Review</div>
                    <div class="text-xl sm:text-2xl font-bold text-blue-400 mt-1.5">{under_review}</div>
                </div>
                <div class="bg-[#161A22] border border-emerald-500/30 rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-emerald-400">Approved</div>
                    <div class="text-xl sm:text-2xl font-bold text-emerald-400 mt-1.5">{approved}</div>
                </div>
                <div class="bg-[#161A22] border border-rose-500/30 rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-rose-400">Rejected</div>
                    <div class="text-xl sm:text-2xl font-bold text-rose-400 mt-1.5">{rejected}</div>
                </div>
                <div class="bg-[#161A22] border border-orange-500/30 rounded-xl p-4">
                    <div class="text-[11px] font-semibold uppercase tracking-wider text-orange-400">Info Requested</div>
                    <div class="text-xl sm:text-2xl font-bold text-orange-400 mt-1.5">{add_info}</div>
                </div>
            </div>

            <!-- Filters -->
            <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-4 sm:p-5">
                <form method="GET" action="/admin/kyc" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                    <div>
                        <label for="search" class="block text-[11px] font-semibold text-[#8F9CAE] mb-1">Search Customer</label>
                        <input type="text" id="search" name="search" value="{search_q}" placeholder="Name, Email, Account #" class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-3.5 py-2 text-xs text-white">
                    </div>
                    <div>
                        <label for="status" class="block text-[11px] font-semibold text-[#8F9CAE] mb-1">Verification Status</label>
                        <select id="status" name="status" class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-3.5 py-2 text-xs text-white">
                            <option value="">All Statuses</option>
                            <option value="pending_review" {'selected' if status_filter == 'pending_review' else ''}>Pending Review</option>
                            <option value="under_review" {'selected' if status_filter == 'under_review' else ''}>Under Review</option>
                            <option value="approved" {'selected' if status_filter == 'approved' else ''}>Approved</option>
                            <option value="rejected" {'selected' if status_filter == 'rejected' else ''}>Rejected</option>
                            <option value="additional_info_required" {'selected' if status_filter == 'additional_info_required' else ''}>Additional Info Required</option>
                        </select>
                    </div>
                    <div>
                        <label for="document_type" class="block text-[11px] font-semibold text-[#8F9CAE] mb-1">Document Type</label>
                        <select id="document_type" name="document_type" class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-3.5 py-2 text-xs text-white">
                            <option value="">All Documents</option>
                            <option value="Passport" {'selected' if doc_filter == 'Passport' else ''}>Passport</option>
                            <option value="Driver's License" {'selected' if doc_filter == "Driver's License" else ''}>Driver's License</option>
                            <option value="National ID Card" {'selected' if doc_filter == 'National ID Card' else ''}>National ID Card</option>
                        </select>
                    </div>
                    <div class="flex items-end gap-2">
                        <button type="submit" class="w-full bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-semibold py-2 px-4 rounded-xl shadow-md transition-all">Apply Filters</button>
                        <a href="/admin/kyc" class="bg-[#0F131A] hover:bg-white/5 border border-[#282E3E] text-[#8F9CAE] text-xs font-semibold py-2 px-3 rounded-xl text-center">Reset</a>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl overflow-hidden shadow-xl">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-[#282E3E] bg-[#0F131A]/60 text-[11px] uppercase tracking-wider text-[#8F9CAE]">
                                <th class="py-3.5 px-4 font-semibold">Customer</th>
                                <th class="py-3.5 px-4 font-semibold">Account Number</th>
                                <th class="py-3.5 px-4 font-semibold">Document Type</th>
                                <th class="py-3.5 px-4 font-semibold">Submission Date</th>
                                <th class="py-3.5 px-4 font-semibold">KYC Status</th>
                                <th class="py-3.5 px-4 font-semibold">Last Updated</th>
                                <th class="py-3.5 px-4 font-semibold text-right">Review Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#282E3E] text-xs">
                            {rows_html}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Admin KYC Review Modal -->
        <div id="kyc-review-modal" class="hidden fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto">
            <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl max-w-2xl w-full p-6 sm:p-8 shadow-2xl relative my-8">
                <button type="button" onclick="closeReviewModal()" class="absolute top-5 right-5 text-[#8F9CAE] hover:text-white p-2">
                    <i class="fa-solid fa-xmark text-lg"></i>
                </button>
                <div class="space-y-6">
                    <div>
                        <div class="text-[11px] font-bold uppercase tracking-wider text-[#246BFD]">Compliance Dossier</div>
                        <h2 id="modal-customer-name" class="text-xl font-bold text-white mt-0.5"></h2>
                        <div id="modal-customer-meta" class="text-xs text-[#8F9CAE] mt-0.5"></div>
                    </div>

                    <div class="bg-[#0F131A] border border-[#282E3E] rounded-xl p-4 grid grid-cols-2 gap-4 text-xs">
                        <div>
                            <span class="block text-[#8F9CAE]">Document Type</span>
                            <span id="modal-doc-type" class="font-semibold text-white"></span>
                        </div>
                        <div>
                            <span class="block text-[#8F9CAE]">Document ID Number</span>
                            <span id="modal-doc-id" class="font-mono font-semibold text-white"></span>
                        </div>
                        <div>
                            <span class="block text-[#8F9CAE]">Submission Date</span>
                            <span id="modal-doc-date" class="font-semibold text-white"></span>
                        </div>
                        <div>
                            <span class="block text-[#8F9CAE]">Current Status</span>
                            <span id="modal-doc-status" class="font-semibold"></span>
                        </div>
                    </div>

                    <div class="bg-[#161A22] border border-[#282E3E] rounded-xl p-4 flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-lg bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center">
                                <i class="fa-solid fa-file-shield text-base"></i>
                            </div>
                            <div>
                                <div class="text-xs font-semibold text-white">Document File Attached</div>
                                <div class="text-[11px] text-[#8F9CAE]">Encrypted storage preview</div>
                            </div>
                        </div>
                        <a id="modal-doc-link" href="#" target="_blank" class="px-3 py-1.5 rounded-lg bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-semibold shadow transition-all">
                            View Document
                        </a>
                    </div>

                    <div id="modal-history-container" class="hidden bg-[#0F131A] border border-[#282E3E] rounded-xl p-4 text-xs space-y-1">
                        <div class="font-semibold text-[#8F9CAE] uppercase text-[10px] tracking-wider">Compliance Review Notes:</div>
                        <div id="modal-history-text" class="text-white"></div>
                    </div>

                    <div class="border-t border-[#282E3E] pt-5 space-y-4">
                        <div class="text-xs font-bold text-white uppercase tracking-wider">Compliance Decisions:</div>

                        <form id="form-start-review" method="POST" action="" class="inline-block mr-2">
                            <button type="submit" class="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold shadow transition-all">
                                Start Review
                            </button>
                        </form>

                        <form id="form-approve" method="POST" action="" class="space-y-3 pt-3 border-t border-[#282E3E]">
                            <div>
                                <label class="block text-[11px] font-semibold text-[#8F9CAE] mb-1">Approval Notes (Optional)</label>
                                <input type="text" name="notes" placeholder="e.g. Document verified, DOB matches registry." class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-3 py-1.5 text-xs text-white">
                            </div>
                            <button type="submit" onclick="return confirm('Approve this KYC submission?')" class="w-full sm:w-auto px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold shadow transition-all">
                                Approve KYC & Unlock Tier 2
                            </button>
                        </form>

                        <form id="form-reject" method="POST" action="" class="space-y-3 pt-3 border-t border-[#282E3E]">
                            <div>
                                <label class="block text-[11px] font-semibold text-rose-400 mb-1">Rejection Reason (Required) *</label>
                                <input type="text" name="reason" required placeholder="e.g. Document image is blurry or expired." class="w-full bg-[#0F131A] border border-rose-500/40 rounded-xl px-3 py-1.5 text-xs text-white">
                            </div>
                            <button type="submit" onclick="return confirm('Reject this KYC submission? Customer will be notified.')" class="w-full sm:w-auto px-5 py-2.5 rounded-xl bg-rose-600 hover:bg-rose-500 text-white text-xs font-semibold shadow transition-all">
                                Reject KYC
                            </button>
                        </form>

                        <form id="form-request-info" method="POST" action="" class="space-y-3 pt-3 border-t border-[#282E3E]">
                            <div>
                                <label class="block text-[11px] font-semibold text-orange-400 mb-1">Requested Information (Required) *</label>
                                <input type="text" name="notes" required placeholder="e.g. Please upload the back side of your ID card." class="w-full bg-[#0F131A] border border-orange-500/40 rounded-xl px-3 py-1.5 text-xs text-white">
                            </div>
                            <button type="submit" class="w-full sm:w-auto px-5 py-2.5 rounded-xl bg-orange-600 hover:bg-orange-500 text-white text-xs font-semibold shadow transition-all">
                                Request Additional Information
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <script>
        function openReviewModal(sub) {{
            document.getElementById('modal-customer-name').innerText = sub.first_name + ' ' + sub.last_name;
            document.getElementById('modal-customer-meta').innerText = sub.email + ' • Acc: ' + (sub.account_number || 'N/A') + ' • ID #' + sub.user_id;
            document.getElementById('modal-doc-type').innerText = sub.document_type;
            document.getElementById('modal-doc-id').innerText = sub.id_number || 'None provided';
            document.getElementById('modal-doc-date').innerText = sub.submitted_at;
            document.getElementById('modal-doc-status').innerText = (sub.status || '').toUpperCase();
            document.getElementById('modal-doc-link').href = '/admin/kyc/document/' + sub.id;

            const histContainer = document.getElementById('modal-history-container');
            const histText = document.getElementById('modal-history-text');
            if (sub.rejection_reason || sub.notes) {{
                histContainer.classList.remove('hidden');
                histText.innerText = sub.rejection_reason ? ('Rejection Reason: ' + sub.rejection_reason) : ('Notes: ' + sub.notes);
            }} else {{
                histContainer.classList.add('hidden');
            }}

            document.getElementById('form-start-review').action = '/admin/kyc/' + sub.id + '/start-review';
            document.getElementById('form-approve').action = '/admin/kyc/' + sub.id + '/approve';
            document.getElementById('form-reject').action = '/admin/kyc/' + sub.id + '/reject';
            document.getElementById('form-request-info').action = '/admin/kyc/' + sub.id + '/request-info';

            document.getElementById('kyc-review-modal').classList.remove('hidden');
        }}

        function closeReviewModal() {{
            document.getElementById('kyc-review-modal').classList.add('hidden');
        }}

        document.getElementById('kyc-review-modal')?.addEventListener('click', function(e) {{
            if (e.target.id === 'kyc-review-modal') closeReviewModal();
        }});
        </script>'''

        html = build_admin_layout(body, "KYC Compliance Management | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 4. Stock Catalog Management
    if path == "/admin/stocks":
        stocks = STATE.get("stocks", [])
        plans = STATE.get("investment_plans", [])
        total_stocks = len(stocks)
        active_stocks = sum(1 for s in stocks if s.get("status") == "active")
        total_invested = sum(float(i.get("amount", 0)) for i in STATE.get("investments", []))
        total_redeemed = sum(float(i.get("expected_payout", 0)) for i in STATE.get("investments", []) if i.get("status") == "redeemed")

        stocks_rows_html = ""
        for stk in stocks:
            plan = next((p for p in plans if p["id"] == stk.get("default_plan_id")), None)
            plan_name = plan["name"] if plan else "Custom"
            ret_pct = plan["return_percentage"] if plan else 20.0
            dur_hrs = plan["duration_hours"] if plan else 48
            is_active = stk.get("status") == "active"
            stk_json = json.dumps(stk).replace('"', '&quot;')

            stocks_rows_html += f'''
            <tr class="hover:bg-[#1C2028] transition-colors">
                <td class="py-4 px-5">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-1.5 shrink-0">
                            <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">
                                <span class="font-bold text-white">{stk['ticker']}</span>
                                <span class="text-[10px] font-mono px-1.5 py-0.2 rounded bg-blue-500/10 text-blue-400 font-semibold border border-blue-500/20">STOCK</span>
                            </div>
                            <div class="text-[11px] text-gray-400 truncate max-w-[160px]">{stk['name']}</div>
                        </div>
                    </div>
                </td>
                <td class="py-4 px-5 text-gray-300">{stk.get('category', 'Technology')}</td>
                <td class="py-4 px-5 font-semibold text-white">{plan_name}</td>
                <td class="py-4 px-5">
                    <div class="font-mono text-emerald-400 font-bold">+{ret_pct:g}%</div>
                    <div class="text-[10px] text-gray-500">{dur_hrs} hrs duration</div>
                </td>
                <td class="py-4 px-5">
                    <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' if is_active else 'bg-gray-500/10 text-gray-400 border border-gray-500/20'}">
                        {stk.get('status', 'active')}
                    </span>
                </td>
                <td class="py-4 px-5 font-mono text-gray-400">{stk.get('display_order', 0)}</td>
                <td class="py-4 px-5 text-right space-x-2">
                    <button type="button" onclick="openEditStockModal({json.dumps(stk)})" class="px-2.5 py-1.5 rounded-lg bg-[#1F2430] hover:bg-[#246BFD] text-gray-300 hover:text-white text-xs font-semibold transition-colors">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <form action="/admin/stocks/{stk['id']}/toggle-status" method="POST" class="inline">
                        <button type="submit" class="px-2.5 py-1.5 rounded-lg {'bg-amber-500/10 text-amber-400 hover:bg-amber-500/20' if is_active else 'bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20'} text-xs font-semibold transition-colors">
                            <i class="fa-solid {'fa-pause' if is_active else 'fa-play'}"></i>
                        </button>
                    </form>
                    <form action="/admin/stocks/{stk['id']}/delete" method="POST" class="inline" onsubmit="return confirm('Delete this stock?');">
                        <button type="submit" class="px-2.5 py-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 text-xs font-semibold transition-colors">
                            <i class="fa-solid fa-trash"></i>
                        </button>
                    </form>
                </td>
            </tr>
            '''

        plan_options_html = "".join([f'<option value="{p["id"]}">{p["name"]} (+{p["return_percentage"]:g}%, {p["duration_hours"]}h)</option>' for p in plans])

        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 tracking-tight">Stock Catalog & Assets</h2>
                    <p class="text-xs text-gray-400 mt-1">Manage institutional stock offerings, default plan assignments, and visibility in customer dashboard.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/admin/plans" class="px-3.5 py-2 rounded-xl bg-[#171A21] hover:bg-[#202530] text-gray-300 hover:text-white border border-[#292E38] text-xs font-semibold transition-all flex items-center gap-2">
                        <i class="fa-solid fa-layer-group"></i>
                        <span>Investment Plans</span>
                    </a>
                    <button type="button" onclick="openAddStockModal()" class="px-4 py-2 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-bold shadow-lg shadow-blue-500/20 transition-all flex items-center gap-2">
                        <i class="fa-solid fa-plus text-xs"></i>
                        <span>Add New Stock</span>
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-gray-400 font-semibold">Total Stock Assets</div>
                    <div class="text-xl font-bold font-mono text-white mt-1">{total_stocks}</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-emerald-400 font-semibold">Active in Catalog</div>
                    <div class="text-xl font-bold font-mono text-emerald-400 mt-1">{active_stocks}</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-blue-400 font-semibold">Total Capital Allocated</div>
                    <div class="text-xl font-bold font-mono text-blue-400 mt-1">${total_invested:,.2f}</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-purple-400 font-semibold">Total Redemptions</div>
                    <div class="text-xl font-bold font-mono text-purple-400 mt-1">${total_redeemed:,.2f}</div>
                </div>
            </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 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">Stock Asset</th>
                                <th class="py-3.5 px-5">Category</th>
                                <th class="py-3.5 px-5">Default Plan</th>
                                <th class="py-3.5 px-5">Contractual Terms</th>
                                <th class="py-3.5 px-5">Status</th>
                                <th class="py-3.5 px-5">Display Order</th>
                                <th class="py-3.5 px-5 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#292E38]">
                            {stocks_rows_html if stocks_rows_html else '<tr><td colspan="7" class="py-12 text-center text-gray-500">No stocks registered.</td></tr>'}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Add/Edit Stock Modal -->
            <div id="stock-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-xl rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl p-6 sm:p-8 space-y-6 max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between pb-4 border-b border-[#292E38]">
                        <h3 id="stock-modal-title" class="text-base font-bold text-white">Add New Stock</h3>
                        <button type="button" onclick="closeStockModal()" class="text-gray-400 hover:text-white">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>

                    <form id="stock-form" action="/admin/stocks" method="POST" class="space-y-4">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Stock Name *</label>
                                <input type="text" name="name" id="modal-name" required placeholder="e.g. Microsoft Corporation" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Ticker Symbol *</label>
                                <input type="text" name="ticker" id="modal-ticker" required placeholder="e.g. MSFT" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono uppercase text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Category</label>
                                <input type="text" name="category" id="modal-category" value="Technology" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Default Plan</label>
                                <select name="default_plan_id" id="modal-default-plan" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                                    {plan_options_html}
                                </select>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Short Description *</label>
                            <textarea name="short_description" id="modal-description" rows="2" required placeholder="Brief executive summary..." class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]"></textarea>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Status</label>
                                <select name="status" id="modal-status" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                                    <option value="active">Active (Visible)</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Display Order</label>
                                <input type="number" name="display_order" id="modal-order" value="0" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono text-xs 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">Logo URL</label>
                            <input type="text" name="logo_url" id="modal-logo-url" placeholder="/assets/images/stocks/msft.svg" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div class="pt-3 border-t border-[#292E38] flex items-center justify-end gap-3">
                            <button type="button" onclick="closeStockModal()" class="px-4 py-2.5 rounded-xl bg-[#12151B] hover:bg-[#1C2028] text-gray-300 text-xs font-semibold">Cancel</button>
                            <button type="submit" 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">Save Stock</button>
                        </div>
                    </form>
                </div>
            </div>

            <script>
            function openAddStockModal() {{
                document.getElementById('stock-modal-title').textContent = 'Add New Stock';
                document.getElementById('stock-form').action = '/admin/stocks';
                document.getElementById('modal-name').value = '';
                document.getElementById('modal-ticker').value = '';
                document.getElementById('modal-category').value = 'Technology';
                document.getElementById('modal-description').value = '';
                document.getElementById('modal-status').value = 'active';
                document.getElementById('modal-order').value = '0';
                document.getElementById('modal-logo-url').value = '';
                document.getElementById('stock-modal').classList.remove('hidden');
            }}

            function openEditStockModal(stk) {{
                document.getElementById('stock-modal-title').textContent = 'Edit Stock (' + stk.ticker + ')';
                document.getElementById('stock-form').action = '/admin/stocks/' + stk.id + '/update';
                document.getElementById('modal-name').value = stk.name || '';
                document.getElementById('modal-ticker').value = stk.ticker || '';
                document.getElementById('modal-category').value = stk.category || 'Technology';
                document.getElementById('modal-description').value = stk.short_description || '';
                document.getElementById('modal-default-plan').value = stk.default_plan_id || '';
                document.getElementById('modal-status').value = stk.status || 'active';
                document.getElementById('modal-order').value = stk.display_order || 0;
                document.getElementById('modal-logo-url').value = stk.logo_url || '';
                document.getElementById('stock-modal').classList.remove('hidden');
            }}

            function closeStockModal() {{
                document.getElementById('stock-modal').classList.add('hidden');
            }}
            </script>
        </div>
        '''
        html = build_admin_layout(body, "Stock Management & Investment Products | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 5. Investment Plans Management
    if path == "/admin/plans":
        plans = STATE.get("investment_plans", [])
        plans_cards_html = ""
        for p in plans:
            is_active = p.get("status") == "active"
            is_rec = bool(p.get("is_recommended"))
            is_unl = bool(p.get("is_unlimited") or p.get("max_amount") is None)
            min_amt = float(p.get("min_amount", 50))
            max_amt = p.get("max_amount")
            max_str = "Unlimited" if is_unl else f"${float(max_amt):,.2f}"

            plans_cards_html += f'''
            <div class="p-6 rounded-3xl bg-[#171A21] border {'border-[#246BFD]/60 ring-1 ring-[#246BFD]/30' if is_rec else 'border-[#292E38]'} flex flex-col justify-between space-y-6 relative shadow-xl">
                {f'<span class="absolute -top-3 left-6 px-3 py-0.5 rounded-full text-[10px] font-extrabold uppercase bg-[#246BFD] text-white tracking-wider shadow-md">Recommended</span>' if is_rec else ''}
                <div>
                    <div class="flex items-start justify-between">
                        <div>
                            <h3 class="text-base font-bold text-white">{p['name']}</h3>
                            <span class="text-[10px] font-mono text-gray-400 uppercase tracking-wider">{p.get('slug', '')}</span>
                        </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' if is_active else 'bg-gray-500/10 text-gray-400 border border-gray-500/20'}">
                            {p.get('status', 'active')}
                        </span>
                    </div>

                    <div class="my-5 p-4 rounded-2xl bg-[#12151B] border border-[#292E38] text-center">
                        <div class="text-[11px] text-gray-400 uppercase tracking-wider font-semibold">Contractual Return</div>
                        <div class="text-3xl font-extrabold font-mono text-emerald-400 mt-1">+{p['return_percentage']:g}%</div>
                        <div class="text-xs text-gray-500 mt-1 font-mono">{p['duration_hours']} Hours Lock Period</div>
                    </div>

                    <div class="space-y-2 text-xs">
                        <div class="flex items-center justify-between py-1.5 border-b border-[#292E38]">
                            <span class="text-gray-400">Min Allocation:</span>
                            <span class="font-mono font-bold text-white">${min_amt:,.2f}</span>
                        </div>
                        <div class="flex items-center justify-between py-1.5 border-b border-[#292E38]">
                            <span class="text-gray-400">Max Allocation:</span>
                            <span class="font-mono font-bold text-white">{max_str}</span>
                        </div>
                    </div>
                </div>

                <div class="pt-2 border-t border-[#292E38] flex items-center justify-between gap-2">
                    <button type="button" onclick="openEditPlanModal({json.dumps(p)})" class="flex-1 py-2 rounded-xl bg-[#1F2430] hover:bg-[#246BFD] text-gray-200 hover:text-white text-xs font-bold transition-all text-center">
                        Edit Tier
                    </button>
                    <form action="/admin/plans/{p['id']}/toggle-status" method="POST" class="inline">
                        <button type="submit" class="p-2 rounded-xl {'bg-amber-500/10 text-amber-400 hover:bg-amber-500/20' if is_active else 'bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20'} text-xs font-semibold transition-colors">
                            <i class="fa-solid {'fa-pause' if is_active else 'fa-play'}"></i>
                        </button>
                    </form>
                </div>
            </div>
            '''

        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 tracking-tight">Investment Plans & Yield Tiers</h2>
                    <p class="text-xs text-gray-400 mt-1">Configure minimum/maximum allocation thresholds, lock durations, and fixed contractual return rates.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/admin/stocks" class="px-3.5 py-2 rounded-xl bg-[#171A21] hover:bg-[#202530] text-gray-300 hover:text-white border border-[#292E38] text-xs font-semibold transition-all flex items-center gap-2">
                        <i class="fa-solid fa-arrow-trend-up"></i>
                        <span>Stock Assets</span>
                    </a>
                    <button type="button" onclick="openAddPlanModal()" class="px-4 py-2 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-bold shadow-lg shadow-blue-500/20 transition-all flex items-center gap-2">
                        <i class="fa-solid fa-plus text-xs"></i>
                        <span>Create New Plan</span>
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {plans_cards_html}
            </div>

            <!-- Edit/Add Plan Modal -->
            <div id="plan-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]">
                        <h3 id="plan-modal-title" class="text-base font-bold text-white">Edit Investment Plan</h3>
                        <button type="button" onclick="closePlanModal()" class="text-gray-400 hover:text-white">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>

                    <form id="plan-form" action="/admin/plans" method="POST" class="space-y-4">
                        <div>
                            <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Plan Name *</label>
                            <input type="text" name="name" id="plan-modal-name" required class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Min Amount ($) *</label>
                                <input type="number" step="any" name="min_amount" id="plan-modal-min" required class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Max Amount ($)</label>
                                <input type="number" step="any" name="max_amount" id="plan-modal-max" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                        </div>

                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="is_unlimited" id="plan-modal-unlimited" value="1" onchange="toggleUnlimitedMax()" class="rounded bg-[#12151B] border-[#292E38] text-[#246BFD]">
                            <label for="plan-modal-unlimited" class="text-xs text-gray-300">Unlimited Maximum Allocation</label>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Duration (Hours) *</label>
                                <input type="number" name="duration_hours" id="plan-modal-duration" required class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Return (%) *</label>
                                <input type="number" step="any" name="return_percentage" id="plan-modal-return" required class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono text-xs focus:outline-none focus:border-[#246BFD]">
                            </div>
                        </div>

                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="is_recommended" id="plan-modal-recommended" value="1" class="rounded bg-[#12151B] border-[#292E38] text-[#246BFD]">
                            <label for="plan-modal-recommended" class="text-xs text-gray-300">Mark as "Recommended" Plan</label>
                        </div>

                        <div class="pt-3 border-t border-[#292E38] flex items-center justify-end gap-3">
                            <button type="button" onclick="closePlanModal()" class="px-4 py-2.5 rounded-xl bg-[#12151B] hover:bg-[#1C2028] text-gray-300 text-xs font-semibold">Cancel</button>
                            <button type="submit" 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">Save Plan</button>
                        </div>
                    </form>
                </div>
            </div>

            <script>
            function toggleUnlimitedMax() {{
                const isUnl = document.getElementById('plan-modal-unlimited').checked;
                const maxInput = document.getElementById('plan-modal-max');
                if (isUnl) {{
                    maxInput.value = '';
                    maxInput.disabled = true;
                    maxInput.placeholder = 'Unlimited';
                }} else {{
                    maxInput.disabled = false;
                    maxInput.placeholder = '4999.00';
                }}
            }}

            function openAddPlanModal() {{
                document.getElementById('plan-modal-title').textContent = 'Create New Investment Plan';
                document.getElementById('plan-form').action = '/admin/plans';
                document.getElementById('plan-modal-name').value = '';
                document.getElementById('plan-modal-min').value = '50.00';
                document.getElementById('plan-modal-max').value = '100.00';
                document.getElementById('plan-modal-unlimited').checked = false;
                toggleUnlimitedMax();
                document.getElementById('plan-modal-duration').value = '48';
                document.getElementById('plan-modal-return').value = '20.00';
                document.getElementById('plan-modal-recommended').checked = false;
                document.getElementById('plan-modal').classList.remove('hidden');
            }}

            function openEditPlanModal(p) {{
                document.getElementById('plan-modal-title').textContent = 'Edit Plan (' + p.name + ')';
                document.getElementById('plan-form').action = '/admin/plans/' + p.id + '/update';
                document.getElementById('plan-modal-name').value = p.name || '';
                document.getElementById('plan-modal-min').value = p.min_amount || '';
                document.getElementById('plan-modal-max').value = (p.max_amount !== null && p.max_amount !== undefined) ? p.max_amount : '';
                document.getElementById('plan-modal-unlimited').checked = Boolean(p.is_unlimited || p.max_amount === null);
                toggleUnlimitedMax();
                document.getElementById('plan-modal-duration').value = p.duration_hours || '';
                document.getElementById('plan-modal-return').value = p.return_percentage || '';
                document.getElementById('plan-modal-recommended').checked = Boolean(p.is_recommended);
                document.getElementById('plan-modal').classList.remove('hidden');
            }}

            function closePlanModal() {{
                document.getElementById('plan-modal').classList.add('hidden');
            }}
            </script>
        </div>
        '''
        html = build_admin_layout(body, "Investment Plans & Yield Tiers | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 6. User Investments Oversight
    if path == "/admin/investments":
        investments = STATE.get("investments", [])
        total_vol = sum(float(i.get("amount", 0)) for i in investments)
        active_vol = sum(float(i.get("amount", 0)) for i in investments if i.get("status") == "active")
        active_cnt = sum(1 for i in investments if i.get("status") == "active")
        matured_payout = sum(float(i.get("expected_payout", 0)) for i in investments if i.get("status") == "matured")
        matured_cnt = sum(1 for i in investments if i.get("status") == "matured")
        redeemed_vol = sum(float(i.get("expected_payout", 0)) for i in investments if i.get("status") == "redeemed")

        inv_rows_html = ""
        for inv in investments:
            st = str(inv.get("status", "active")).lower()
            badge_class = "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" if st == "matured" else ("bg-purple-500/10 text-purple-400 border border-purple-500/20" if st == "redeemed" else "bg-blue-500/10 text-blue-400 border border-blue-500/20")
            user_rec = STATE.get("user", {})
            user_name = f"{user_rec.get('first_name', 'Customer')} {user_rec.get('last_name', '')}"
            user_email = user_rec.get('email', 'customer@bnkfx.com')

            inv_rows_html += f'''
            <tr class="hover:bg-[#1C2028] transition-colors">
                <td class="py-4 px-5 font-mono font-bold text-blue-400">{inv.get('reference', 'INV')}</td>
                <td class="py-4 px-5">
                    <div class="font-bold text-white">{user_name}</div>
                    <div class="text-[11px] text-gray-500">{user_email}</div>
                </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('return_percentage', 0):g}%)</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('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 {badge_class}">
                        {st}
                    </span>
                </td>
                <td class="py-4 px-5 text-right font-mono text-[11px] text-gray-400">
                    {'Redeemed ' + str(inv.get('redeemed_at', '')) if st == 'redeemed' else 'Active Cycle'}
                </td>
            </tr>
            '''

        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 tracking-tight">User Investment Oversight & Redemptions</h2>
                    <p class="text-xs text-gray-400 mt-1">Audit all platform customer investment allocations, lock periods, maturities, and payout redemptions.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/admin/stocks" class="px-3.5 py-2 rounded-xl bg-[#171A21] hover:bg-[#202530] text-gray-300 hover:text-white border border-[#292E38] text-xs font-semibold transition-all">Stock Catalog</a>
                    <a href="/admin/plans" class="px-3.5 py-2 rounded-xl bg-[#171A21] hover:bg-[#202530] text-gray-300 hover:text-white border border-[#292E38] text-xs font-semibold transition-all">Yield Plans</a>
                </div>
            </div>

            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-gray-400 font-semibold">Total Platform Volume</div>
                    <div class="text-xl font-bold font-mono text-white mt-1">${total_vol:,.2f}</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-blue-400 font-semibold">Active Capital (Locked)</div>
                    <div class="text-xl font-bold font-mono text-blue-400 mt-1">${active_vol:,.2f}</div>
                    <div class="text-[10px] text-gray-500 mt-0.5">{active_cnt} active positions</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-emerald-400 font-semibold">Matured (Unredeemed)</div>
                    <div class="text-xl font-bold font-mono text-emerald-400 mt-1">${matured_payout:,.2f}</div>
                    <div class="text-[10px] text-gray-500 mt-0.5">{matured_cnt} matured positions</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-[10px] uppercase tracking-wider text-purple-400 font-semibold">Total Redeemed Paid</div>
                    <div class="text-xl font-bold font-mono text-purple-400 mt-1">${redeemed_vol:,.2f}</div>
                </div>
            </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 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">Customer</th>
                                <th class="py-3.5 px-5">Stock & Plan</th>
                                <th class="py-3.5 px-5">Invested Amount</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">Audit Details</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-[#292E38]">
                            {inv_rows_html if inv_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>
        '''
        html = build_admin_layout(body, "User Investment Oversight & Redemptions | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 10. Card Products & Applications Administration
    if path == "/admin/cards":
        qs = urllib.parse.parse_qs(parsed.query)
        active_tab = qs.get("tab", ["products"])[0]
        curr_status = qs.get("status", ["all"])[0].lower()
        search_q = qs.get("search", [""])[0].lower()

        products = STATE.get("card_products", [])
        orders = STATE.get("card_orders", [])

        tot_prods = len(products)
        act_prods = sum(1 for p in products if p.get("is_active", 1) == 1)
        inact_prods = tot_prods - act_prods

        tot_apps = len(orders)
        pend_apps = sum(1 for o in orders if o.get("status") in ["pending", "processing"])
        appr_apps = sum(1 for o in orders if o.get("status") in ["completed", "approved", "active"])
        rej_apps = sum(1 for o in orders if o.get("status") == "rejected")

        # Build Products Cards HTML
        prod_cards_html = ""
        for p in products:
            is_act = (p.get("is_active", 1) == 1)
            design = p.get("design", p.get("card_design", "obsidian"))
            if design == "midnight_blue":
                bg_grad = "from-[#0B2545] via-[#133E7C] to-[#1E3A8A] border-blue-400/30"
            elif design == "titanium_gold":
                bg_grad = "from-[#3A2207] via-[#854D0E] to-[#D97706] border-amber-400/30"
            elif design == "crypto_black":
                bg_grad = "from-[#000000] via-[#111827] to-[#1F2937] border-purple-500/30"
            else:
                bg_grad = "from-[#0F1318] via-[#161B22] to-[#21262D] border-gray-700/50"

            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))

            feats_list = p.get("features", [])
            feats_html = "".join([f'<li class="flex items-center gap-2"><i class="fa-solid fa-check text-emerald-400 text-[10px]"></i><span class="truncate">{f}</span></li>' for f in feats_list[:3]])
            if len(feats_list) > 3:
                feats_html += f'<li class="text-[10px] text-gray-500 pl-4">+{len(feats_list) - 3} more benefits</li>'

            p_json_str = html_lib.escape(json.dumps(p), quote=True)
            prod_cards_html += f'''
            <div class="rounded-3xl bg-[#171A21] border border-[#292E38] p-6 flex flex-col justify-between hover:border-gray-500 transition-all shadow-xl">
                <div class="space-y-4">
                    <div class="w-full h-40 rounded-2xl bg-gradient-to-tr {bg_grad} border p-4 text-white flex flex-col justify-between shadow-lg relative overflow-hidden">
                        <div class="absolute -right-6 -bottom-6 w-28 h-28 rounded-full bg-white/5 blur-xl pointer-events-none"></div>
                        <div class="flex justify-between items-center text-xs opacity-90">
                            <span class="font-bold tracking-wide text-[11px]">{p['name']}</span>
                            <span class="font-mono text-sm uppercase font-extrabold tracking-wider">{p.get('network', 'Visa')}</span>
                        </div>
                        <div class="text-sm font-mono tracking-widest opacity-80 py-1">•••• •••• •••• 0000</div>
                        <div class="flex justify-between items-end text-[9px] uppercase tracking-wider opacity-80">
                            <div>
                                <span class="block text-[8px] text-gray-400">Card Type</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-[9px] font-bold bg-white/10">{p.get('design', 'obsidian').upper()}</span>
                        </div>
                    </div>

                    <div class="flex items-center justify-between">
                        <div>
                            <h3 class="text-base font-bold text-white">{p['name']}</h3>
                            <p class="text-xs text-gray-400 capitalize">{p.get('type', 'virtual')} Card • {p.get('network', 'Visa')}</p>
                        </div>
                        <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider {'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' if is_act else 'bg-red-500/10 text-red-400 border border-red-500/20'}">
                            {'● Active' if is_act else '○ Disabled'}
                        </span>
                    </div>

                    <div class="grid grid-cols-2 gap-2 text-xs">
                        <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                            <span class="text-[10px] text-gray-500 uppercase block font-semibold">Issuance Fee</span>
                            <span class="font-mono font-bold {'text-blue-400' if p_fee > 0 else 'text-emerald-400'}">
                                {'$' + f'{p_fee:.2f}' if p_fee > 0 else 'Free ($0.00)'}
                            </span>
                        </div>
                        <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                            <span class="text-[10px] text-gray-500 uppercase block font-semibold">Min Balance Req.</span>
                            <span class="font-mono font-bold text-white">
                                {'$' + f'{p_min_bal:.2f}' if p_min_bal > 0 else 'None ($0.00)'}
                            </span>
                        </div>
                        <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                            <span class="text-[10px] text-gray-500 uppercase block font-semibold">Daily Spend Limit</span>
                            <span class="font-mono font-bold text-white">${p_daily_lim:,.2f}</span>
                        </div>
                        <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                            <span class="text-[10px] text-gray-500 uppercase block font-semibold">Monthly Limit</span>
                            <span class="font-mono font-bold text-white">${p_monthly_lim:,.2f}</span>
                        </div>
                    </div>

                    <ul class="space-y-1.5 text-xs text-gray-300">
                        {feats_html}
                    </ul>
                </div>

                <div class="pt-5 border-t border-[#292E38] flex items-center justify-between gap-2">
                    <form method="POST" action="/admin/cards/products/{p['id']}/toggle-status" class="inline">
                        <button type="submit" class="px-3 py-2 rounded-xl text-xs font-semibold transition-all {'bg-[#1F2430] hover:bg-amber-500/20 text-gray-300 hover:text-amber-400' if is_act else 'bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400'}">
                            <i class="fa-solid {'fa-pause' if is_act else 'fa-play'} mr-1"></i>
                            {'Disable' if is_act else 'Activate'}
                        </button>
                    </form>
                    <button type="button" onclick="openEditProductModal({p_json_str})"
                        class="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs shadow-md transition-all">
                        <i class="fa-solid fa-pen-to-square mr-1"></i>
                        Edit Product
                    </button>
                </div>
            </div>'''

        # Filter Applications
        filtered_orders = []
        for o in orders:
            o_st = str(o.get("status", "pending")).lower()
            if curr_status == "pending" and o_st not in ["pending", "processing"]:
                continue
            elif curr_status in ["completed", "approved"] and o_st not in ["completed", "approved", "active"]:
                continue
            elif curr_status == "rejected" and o_st != "rejected":
                continue

            if search_q:
                haystack = f"{o.get('reference', '')} {o.get('user_name', '')} {o.get('email', '')} {o.get('product_name', '')}".lower()
                if search_q not in haystack:
                    continue
            filtered_orders.append(o)

        app_rows_html = ""
        for o in filtered_orders:
            o_st = str(o.get("status", "pending")).lower()
            is_pending = o_st in ["pending", "processing"]
            is_approved = o_st in ["completed", "approved", "active"]
            is_rejected = (o_st == "rejected")

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

            if is_pending:
                st_pill = '<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-clock-rotate-left text-[9px]"></i> Pending Review</span>'
                actions_html = f'''
                <div class="flex items-center justify-end gap-2">
                    <form method="POST" action="/admin/cards/applications/{o['id']}/approve" onsubmit="return confirm('Approve this application and issue virtual credentials immediately?')">
                        <button type="submit" class="px-3 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs transition-all shadow-md">
                            <i class="fa-solid fa-check mr-1"></i> Approve
                        </button>
                    </form>
                    <button type="button" onclick="openRejectModal({o['id']}, '{o_ref}', {o_fee})"
                        class="px-3 py-1.5 rounded-xl bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 font-semibold text-xs transition-all">
                        <i class="fa-solid fa-xmark mr-1"></i> Reject
                    </button>
                </div>'''
            elif is_approved:
                st_pill = '<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>'
                actions_html = '<span class="text-[11px] font-mono text-gray-500">Live on Account</span>'
            elif is_rejected:
                rej_reason = html_lib.escape(str(o.get("rejection_reason", "Compliance criteria not met")))
                st_pill = 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 (Refunded)
                    </span>
                    <p class="text-[10px] text-gray-400 italic max-w-xs truncate" title="{rej_reason}">"{rej_reason}"</p>
                </div>'''
                actions_html = '<span class="text-[11px] font-mono text-rose-400/60">Refund Settled</span>'
            else:
                st_pill = 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>'
                actions_html = '—'

            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">
                    <div class="font-bold text-white">{o.get('user_name', 'Abraham Elom')}</div>
                    <div class="text-[11px] text-gray-400 font-mono">{o.get('email', '—')}</div>
                </td>
                <td class="py-4">
                    <div class="font-semibold text-white">{o.get('product_name', 'Virtual Card')}</div>
                    <div class="text-[10px] text-gray-400 capitalize">{o.get('card_type', 'virtual')} • {o.get('network', 'Visa')}</div>
                </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'}
                </td>
                <td class="py-4 font-mono text-gray-300">
                    {f'${o_min_bal:.2f}' if o_min_bal > 0 else '$0.00'}
                </td>
                <td class="py-4 text-gray-400 font-mono text-[11px]">{o.get('created_at', time.strftime('%Y-%m-%d %H:%M'))}</td>
                <td class="py-4">{st_pill}</td>
                <td class="py-4 text-right">{actions_html}</td>
            </tr>'''

        body = f'''
        <div class="space-y-6">
            <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="/admin" class="hover:text-white transition-colors">Admin</a>
                        <span>/</span>
                        <span class="text-white">Card Management</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Virtual & Physical Card Management</h1>
                    <p class="text-xs text-gray-400 mt-1">Configure card products, manage issuance limits & eligibility requirements, and process customer card applications.</p>
                </div>
                <div class="flex items-center gap-3">
                    <button type="button" onclick="openCreateProductModal()"
                        class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-semibold text-xs shadow-lg shadow-blue-500/20 transition-all active:scale-95">
                        <i class="fa-solid fa-plus text-xs"></i>
                        <span>Add Card Product</span>
                    </button>
                </div>
            </div>

            <!-- 7 KPI Metric Cards -->
            <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3">
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Total Products</span>
                    <div class="text-xl font-bold font-mono text-white">{tot_prods}</div>
                    <div class="text-[10px] text-gray-500">Configured tiers</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Active Catalog</span>
                    <div class="text-xl font-bold font-mono text-emerald-400">{act_prods}</div>
                    <div class="text-[10px] text-emerald-500/80">Available to users</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Suspended</span>
                    <div class="text-xl font-bold font-mono text-amber-400">{inact_prods}</div>
                    <div class="text-[10px] text-gray-500">Hidden from catalog</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Applications</span>
                    <div class="text-xl font-bold font-mono text-white">{tot_apps}</div>
                    <div class="text-[10px] text-gray-500">All submissions</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1 relative overflow-hidden">
                    <span class="text-[10px] font-bold text-amber-400 uppercase tracking-wider block">Pending Review</span>
                    <div class="text-xl font-bold font-mono text-amber-300">{pend_apps}</div>
                    <div class="text-[10px] text-amber-400/80">Awaiting action</div>
                    {'<div class="absolute top-2 right-2 w-2 h-2 rounded-full bg-amber-400 animate-ping"></div>' if pend_apps > 0 else ''}
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Issued / Active</span>
                    <div class="text-xl font-bold font-mono text-blue-400">{appr_apps}</div>
                    <div class="text-[10px] text-blue-400/80">Live customer cards</div>
                </div>
                <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1">
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block">Rejected</span>
                    <div class="text-xl font-bold font-mono text-rose-400">{rej_apps}</div>
                    <div class="text-[10px] text-rose-400/80">Fees refunded</div>
                </div>
            </div>

            <!-- Navigation Tabs -->
            <div class="flex items-center gap-2 border-b border-[#292E38] pb-1">
                <button type="button" onclick="switchAdminTab('products')" id="tab-btn-products"
                    class="px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 {'bg-[#246BFD] text-white shadow-md' if active_tab == 'products' else 'text-gray-400 hover:text-white hover:bg-[#171A21]'}">
                    <i class="fa-solid fa-layer-group"></i>
                    <span>Card Products Catalog</span>
                    <span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono bg-black/30">{tot_prods}</span>
                </button>
                <button type="button" onclick="switchAdminTab('applications')" id="tab-btn-applications"
                    class="px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 {'bg-[#246BFD] text-white shadow-md' if active_tab == 'applications' else 'text-gray-400 hover:text-white hover:bg-[#171A21]'}">
                    <i class="fa-solid fa-inbox"></i>
                    <span>Card Applications</span>
                    {f'<span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono bg-amber-500/20 text-amber-300 border border-amber-500/30">{pend_apps}</span>' if pend_apps > 0 else f'<span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono bg-black/30">{tot_apps}</span>'}
                </button>
            </div>

            <!-- TAB 1: CARD PRODUCTS CATALOG -->
            <div id="tab-section-products" class="{'block' if active_tab == 'products' else 'hidden'} space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    {prod_cards_html if prod_cards_html else '<div class="col-span-full p-12 text-center text-gray-500">No card products configured.</div>'}
                </div>
            </div>

            <!-- TAB 2: CARD APPLICATIONS -->
            <div id="tab-section-applications" class="{'block' if active_tab == 'applications' else 'hidden'} space-y-4">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 p-4 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="flex items-center gap-2 overflow-x-auto">
                        <a href="/admin/cards?tab=applications&status=all"
                            class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-[#246BFD] text-white' if curr_status == 'all' else 'bg-[#12151B] text-gray-400 hover:text-white'}">
                            All ({tot_apps})
                        </a>
                        <a href="/admin/cards?tab=applications&status=pending"
                            class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-amber-500 text-black font-bold' if curr_status == 'pending' else 'bg-[#12151B] text-amber-400 hover:bg-amber-500/10'}">
                            Pending ({pend_apps})
                        </a>
                        <a href="/admin/cards?tab=applications&status=completed"
                            class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-emerald-600 text-white' if curr_status in ['completed', 'approved'] else 'bg-[#12151B] text-emerald-400 hover:bg-emerald-500/10'}">
                            Approved ({appr_apps})
                        </a>
                        <a href="/admin/cards?tab=applications&status=rejected"
                            class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-rose-600 text-white' if curr_status == 'rejected' else 'bg-[#12151B] text-rose-400 hover:bg-rose-500/10'}">
                            Rejected ({rej_apps})
                        </a>
                    </div>

                    <form method="GET" action="/admin/cards" class="flex items-center gap-2">
                        <input type="hidden" name="tab" value="applications">
                        <input type="hidden" name="status" value="{curr_status}">
                        <div class="relative">
                            <i class="fa-solid fa-magnifying-glass absolute left-3 top-2.5 text-xs text-gray-500"></i>
                            <input type="text" name="search" value="{search_q}" placeholder="Search applicant or order ref..."
                                class="pl-9 pr-3 py-1.5 rounded-xl bg-[#12151B] border border-[#292E38] text-xs text-white placeholder-gray-500 focus:outline-none focus:border-[#246BFD] w-56 sm:w-64">
                        </div>
                        <button type="submit" class="px-3 py-1.5 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-gray-300 text-xs font-semibold">Filter</button>
                        {f'<a href="/admin/cards?tab=applications&status={curr_status}" class="text-xs text-gray-400 hover:text-white px-1">Clear</a>' if search_q else ''}
                    </form>
                </div>

                <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] space-y-4">
                    <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">Applicant / Customer</th>
                                    <th class="pb-3">Card Product</th>
                                    <th class="pb-3">Fee Paid</th>
                                    <th class="pb-3">Req. Balance</th>
                                    <th class="pb-3">Date</th>
                                    <th class="pb-3">Status</th>
                                    <th class="pb-3 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-[#292E38]/60">
                                {app_rows_html if app_rows_html else '<tr><td colspan="8" 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 found</p><p class="text-[11px] text-gray-500">Customer submissions will appear here for review and issuance.</p></td></tr>'}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Create Card Product Modal -->
        <div id="create-product-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-xl 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]">
                    <div>
                        <h3 class="text-lg font-bold text-white">Create Card Product</h3>
                        <p class="text-xs text-gray-400">Configure catalog tier, fee, eligibility minimum, and limits.</p>
                    </div>
                    <button type="button" onclick="closeCreateProductModal()" 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>

                <form method="POST" action="/admin/cards/products" class="space-y-4 text-xs">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Product Name *</label>
                            <input type="text" name="name" required placeholder="e.g. Monveracu Obsidian Virtual"
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-medium focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Card Type *</label>
                            <select name="card_type" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="virtual">Virtual Card</option>
                                <option value="physical">Physical Card</option>
                                <option value="metal">Metal Card</option>
                                <option value="crypto_black">Crypto Black VIP</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Payment Network *</label>
                            <select name="network" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="Monveracu Pay">Monveracu Pay</option>
                                <option value="Monveracu VIP">Monveracu VIP</option>
                                <option value="Visa">Visa</option>
                                <option value="Mastercard">Mastercard</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Visual Design Theme *</label>
                            <select name="card_design" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="obsidian">Obsidian Black</option>
                                <option value="midnight_blue">Midnight Blue Platinum</option>
                                <option value="titanium_gold">Titanium Gold Edition</option>
                                <option value="crypto_black">Crypto Black VIP</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Issuance Fee ($) *</label>
                            <input type="number" step="0.01" min="0" name="issuance_fee" value="0.00" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Min Balance Required ($)</label>
                            <input type="number" step="0.01" min="0" name="min_balance_required" value="0.00" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Daily Spend Limit ($)</label>
                            <input type="number" step="0.01" min="10" name="daily_limit" value="5000.00" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Monthly Spend Limit ($)</label>
                            <input type="number" step="0.01" min="10" name="monthly_limit" value="25000.00" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Status</label>
                            <select name="is_active" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="1">Active (Enabled in Catalog)</option>
                                <option value="0">Disabled (Hidden)</option>
                            </select>
                        </div>

                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Short Description</label>
                            <input type="text" name="description" placeholder="e.g. Free virtual card for digital payments & subscriptions."
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Features & Benefits (one per line)</label>
                            <textarea name="features" rows="4" placeholder="Instant Issuance&#10;Apple Pay & Google Pay&#10;Zero FX Fees&#10;Dynamic CVV Security"
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]"></textarea>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-3 border-t border-[#292E38]">
                        <button type="button" onclick="closeCreateProductModal()" class="px-4 py-2.5 rounded-xl bg-[#1F2430] text-gray-300 font-semibold hover:bg-[#252B3B] transition-all">
                            Cancel
                        </button>
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold shadow-lg shadow-blue-500/20 transition-all">
                            Create Card Product
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Edit Card Product Modal -->
        <div id="edit-product-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-xl 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]">
                    <div>
                        <h3 class="text-lg font-bold text-white">Edit Card Product</h3>
                        <p class="text-xs text-gray-400" id="edit-modal-subtitle">Modify parameters and fees for this card product.</p>
                    </div>
                    <button type="button" onclick="closeEditProductModal()" 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>

                <form id="edit-product-form" method="POST" action="" class="space-y-4 text-xs">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Product Name *</label>
                            <input type="text" id="edit-name" name="name" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-medium focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Card Type *</label>
                            <select id="edit-card_type" name="card_type" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="virtual">Virtual Card</option>
                                <option value="physical">Physical Card</option>
                                <option value="metal">Metal Card</option>
                                <option value="crypto_black">Crypto Black VIP</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Payment Network *</label>
                            <select id="edit-network" name="network" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="Visa">Visa</option>
                                <option value="Mastercard">Mastercard</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Visual Design Theme *</label>
                            <select id="edit-card_design" name="card_design" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="obsidian">Obsidian Black</option>
                                <option value="midnight_blue">Midnight Blue Platinum</option>
                                <option value="titanium_gold">Titanium Gold Edition</option>
                                <option value="crypto_black">Crypto Black VIP</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Issuance Fee ($) *</label>
                            <input type="number" step="0.01" min="0" id="edit-issuance_fee" name="issuance_fee" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Min Balance Required ($)</label>
                            <input type="number" step="0.01" min="0" id="edit-min_balance_required" name="min_balance_required" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Daily Spend Limit ($)</label>
                            <input type="number" step="0.01" min="10" id="edit-daily_limit" name="daily_limit" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Monthly Spend Limit ($)</label>
                            <input type="number" step="0.01" min="10" id="edit-monthly_limit" name="monthly_limit" required
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white font-mono focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div>
                            <label class="block text-gray-400 mb-1 font-semibold">Status</label>
                            <select id="edit-is_active" name="is_active" class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                                <option value="1">Active (Enabled)</option>
                                <option value="0">Disabled (Hidden)</option>
                            </select>
                        </div>

                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Short Description</label>
                            <input type="text" id="edit-description" name="description"
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]">
                        </div>

                        <div class="sm:col-span-2">
                            <label class="block text-gray-400 mb-1 font-semibold">Features & Benefits (one per line)</label>
                            <textarea id="edit-features" name="features" rows="4"
                                class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-[#246BFD]"></textarea>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-3 border-t border-[#292E38]">
                        <button type="button" onclick="closeEditProductModal()" class="px-4 py-2.5 rounded-xl bg-[#1F2430] text-gray-300 font-semibold hover:bg-[#252B3B] transition-all">
                            Cancel
                        </button>
                        <button type="submit" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold shadow-lg shadow-blue-500/20 transition-all">
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Reject Application Modal -->
        <div id="reject-app-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="text-center space-y-1">
                    <div class="w-12 h-12 rounded-2xl bg-rose-500/10 text-rose-400 flex items-center justify-center mx-auto text-xl mb-2">
                        <i class="fa-solid fa-triangle-exclamation"></i>
                    </div>
                    <h3 class="text-lg font-bold text-white">Reject Card Application</h3>
                    <p class="text-xs text-gray-400" id="reject-modal-desc">Document the rejection reason. Any issuance fee paid will be refunded to customer balance.</p>
                </div>

                <form id="reject-app-form" method="POST" action="" class="space-y-4 text-xs">
                    <div>
                        <label class="block text-gray-400 mb-1 font-semibold">Rejection Reason *</label>
                        <textarea name="reason" rows="3" required placeholder="e.g. Account does not meet minimum verification requirements or KYC incomplete."
                            class="w-full px-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white focus:outline-none focus:border-rose-500"></textarea>
                    </div>

                    <div class="p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-300 text-[11px] space-y-1">
                        <p class="font-bold"><i class="fa-solid fa-circle-info mr-1"></i> Refund Policy Automation:</p>
                        <p>If an issuance fee was debited upon submission, the exact amount will be refunded directly to the user's available USD ledger balance.</p>
                    </div>

                    <div class="grid grid-cols-2 gap-3 pt-2">
                        <button type="button" onclick="closeRejectModal()" class="py-2.5 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-gray-300 font-semibold text-xs">
                            Cancel
                        </button>
                        <button type="submit" class="py-2.5 rounded-xl bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs shadow-lg shadow-rose-600/30">
                            Confirm Rejection
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <script>
        function switchAdminTab(tab) {{
            const pSec = document.getElementById('tab-section-products');
            const aSec = document.getElementById('tab-section-applications');
            const pBtn = document.getElementById('tab-btn-products');
            const aBtn = document.getElementById('tab-btn-applications');

            if (tab === 'products') {{
                pSec.classList.remove('hidden');
                pSec.classList.add('block');
                aSec.classList.add('hidden');
                aSec.classList.remove('block');

                pBtn.className = 'px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 bg-[#246BFD] text-white shadow-md';
                aBtn.className = 'px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 text-gray-400 hover:text-white hover:bg-[#171A21]';
            }} else {{
                aSec.classList.remove('hidden');
                aSec.classList.add('block');
                pSec.classList.add('hidden');
                pSec.classList.remove('block');

                aBtn.className = 'px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 bg-[#246BFD] text-white shadow-md';
                pBtn.className = 'px-4 py-2.5 rounded-xl font-semibold text-xs transition-all flex items-center gap-2 text-gray-400 hover:text-white hover:bg-[#171A21]';
            }}
        }}

        function openCreateProductModal() {{
            document.getElementById('create-product-modal').classList.remove('hidden');
        }}

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

        function openEditProductModal(p) {{
            document.getElementById('edit-product-form').action = '/admin/cards/products/' + p.id + '/update';
            document.getElementById('edit-modal-subtitle').textContent = 'Editing ' + (p.name || 'Card Product');
            document.getElementById('edit-name').value = p.name || '';
            document.getElementById('edit-card_type').value = p.card_type || p.type || 'virtual';
            document.getElementById('edit-network').value = p.network || 'Visa';
            document.getElementById('edit-card_design').value = p.card_design || p.design || 'obsidian';
            document.getElementById('edit-issuance_fee').value = parseFloat(p.issuance_fee || p.fee || 0).toFixed(2);
            document.getElementById('edit-min_balance_required').value = parseFloat(p.min_balance_required || 0).toFixed(2);
            document.getElementById('edit-daily_limit').value = parseFloat(p.daily_limit || p.limit || 5000).toFixed(2);
            document.getElementById('edit-monthly_limit').value = parseFloat(p.monthly_limit || 25000).toFixed(2);
            document.getElementById('edit-is_active').value = (p.is_active !== undefined ? (p.is_active ? 1 : 0) : 1);
            document.getElementById('edit-description').value = p.description || '';

            const feats = p.features || [];
            document.getElementById('edit-features').value = feats.join('\\n');

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

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

        function openRejectModal(id, ref, fee) {{
            document.getElementById('reject-app-form').action = '/admin/cards/applications/' + id + '/reject';
            document.getElementById('reject-modal-desc').textContent = 'Order ' + ref + ' (Fee: $' + fee.toFixed(2) + '). Rejection refunds fee to user.';
            document.getElementById('reject-app-modal').classList.remove('hidden');
        }}

        function closeRejectModal() {{
            document.getElementById('reject-app-modal').classList.add('hidden');
        }}
        </script>
        '''
        html = build_admin_layout(body, "Card Marketplace Administration | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 10. Email Settings Admin View
    if path in ["/admin/settings/email", "/admin/email-settings"]:
        settings = mail_service.get_email_settings(STATE)
        email_logs = STATE.get("email_logs", [])
        total_emails = len(email_logs)
        sent_emails = sum(1 for e in email_logs if e.get("status") in ["sent", "delivered"])
        failed_emails = sum(1 for e in email_logs if e.get("status") == "failed")
        success_pct = f"{(sent_emails / total_emails * 100):.1f}%" if total_emails > 0 else "100.0%"

        triggers = [
            ("notify_welcome", "Customer Welcome Notifications", "Sent immediately upon customer registration with account details.", settings.get("notify_welcome", True)),
            ("notify_transactions", "Financial Transaction Confirmations", "Sent when money transfers, exchanges, or fee settlements finalize.", settings.get("notify_transactions", True)),
            ("notify_security", "Security & Access Alerts", "Sent on logins, password modifications, and security setting updates.", settings.get("notify_security", True)),
            ("notify_password_reset", "Password Reset Recovery Links", "Sent when users request password recovery with single-use tokens.", settings.get("notify_password_reset", True)),
            ("notify_deposits", "Crypto & Fiat Deposit Updates", "Sent when deposits are initiated, confirmed, credited, or rejected.", settings.get("notify_deposits", True)),
            ("notify_withdrawals", "Withdrawal Status Updates", "Sent when customer withdrawal disbursements process.", settings.get("notify_withdrawals", True)),
            ("notify_cards", "Virtual Card Application & Issuance", "Sent when card applications are submitted, approved, or declined.", settings.get("notify_cards", True)),
        ]
        active_triggers_count = sum(1 for _, _, _, enabled in triggers if enabled)

        query = urllib.parse.parse_qs(parsed.query)
        saved_banner = ""
        if "saved" in query:
            saved_banner = '''
            <div class="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm flex items-center justify-between shadow-lg">
                <div class="flex items-center gap-3">
                    <i class="fa-solid fa-circle-check text-xl text-emerald-400"></i>
                    <div>
                        <div class="font-bold">Settings Persisted Successfully</div>
                        <div class="text-xs text-emerald-400/80">SMTP credentials and notification policies have been committed to the runtime environment.</div>
                    </div>
                </div>
                <button type="button" onclick="this.parentElement.remove()" class="text-emerald-400/60 hover:text-emerald-400">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            '''

        triggers_html = ""
        for field_name, title_text, desc_text, is_enabled in triggers:
            checked = "checked" if is_enabled else ""
            triggers_html += f'''
            <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between transition-colors hover:border-[#384050]">
                <div class="pr-4">
                    <div class="text-sm font-semibold text-white">{title_text}</div>
                    <div class="text-xs text-[#8F9CAE] mt-0.5">{desc_text}</div>
                </div>
                <label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
                    <input type="checkbox" name="{field_name}" value="1" {checked} class="sr-only peer">
                    <div class="w-11 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#246BFD]"></div>
                </label>
            </div>
            '''

        require_verif_checked = "checked" if settings.get("require_email_verification", True) else ""

        body = f'''
        <div class="max-w-7xl mx-auto space-y-6">
            <!-- Breadcrumbs & Header -->
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <div class="flex items-center gap-2 text-xs text-[#8F9CAE] mb-1">
                        <a href="/admin" class="hover:text-white">Admin</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <span class="text-white font-medium">Email Settings & SMTP Configuration</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Email System Management</h1>
                    <p class="text-xs text-[#8F9CAE] mt-1">Configure SMTP delivery gateways, credentials, security verification rules, and automated transactional events.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/admin/email-logs" class="px-4 py-2 rounded-xl bg-[#171A21] hover:bg-[#202634] text-white border border-[#292E38] text-xs font-semibold flex items-center gap-2 transition-all">
                        <i class="fa-solid fa-paper-plane text-[#246BFD]"></i>
                        <span>Inspect Delivery Logs</span>
                    </a>
                </div>
            </div>

            {saved_banner}

            <!-- KPI Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="flex items-center justify-between text-xs text-[#8F9CAE] mb-2 font-medium">
                        <span>Total Emails Dispatched</span>
                        <i class="fa-solid fa-envelope text-[#246BFD]"></i>
                    </div>
                    <div class="text-2xl font-bold text-white font-mono">{total_emails}</div>
                    <div class="text-[11px] text-emerald-400 mt-1 flex items-center gap-1">
                        <i class="fa-solid fa-circle-check text-[10px]"></i>
                        <span>{sent_emails} sent successfully</span>
                    </div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="flex items-center justify-between text-xs text-[#8F9CAE] mb-2 font-medium">
                        <span>Delivery Reliability</span>
                        <i class="fa-solid fa-chart-line text-[#20C997]"></i>
                    </div>
                    <div class="text-2xl font-bold text-white font-mono">{success_pct}</div>
                    <div class="text-[11px] text-[#8F9CAE] mt-1">
                        {failed_emails} reported delivery failures
                    </div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="flex items-center justify-between text-xs text-[#8F9CAE] mb-2 font-medium">
                        <span>Active Triggers</span>
                        <i class="fa-solid fa-bolt text-[#F5B942]"></i>
                    </div>
                    <div class="text-2xl font-bold text-white font-mono">{active_triggers_count} <span class="text-xs text-[#8F9CAE] font-normal">/ {len(triggers)} enabled</span></div>
                    <div class="text-[11px] text-[#246BFD] mt-1">
                        Automated event dispatches
                    </div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="flex items-center justify-between text-xs text-[#8F9CAE] mb-2 font-medium">
                        <span>Verification Policy</span>
                        <i class="fa-solid fa-shield-halved text-[#8054F6]"></i>
                    </div>
                    <div class="text-2xl font-bold text-white">
                        {'<span class="text-emerald-400">Enforced</span>' if settings.get("require_email_verification", True) else '<span class="text-amber-400">Optional</span>'}
                    </div>
                    <div class="text-[11px] text-[#8F9CAE] mt-1">
                        Requires email activation
                    </div>
                </div>
            </div>

            <!-- Configuration & Test Grid -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Left 2 Cols: SMTP & Notification Settings Form -->
                <div class="lg:col-span-2 space-y-6">
                    <form method="POST" action="/admin/settings/email" class="space-y-6">
                        <!-- SMTP Server Gateway Card -->
                        <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                            <div class="flex items-center justify-between border-b border-[#292E38] pb-4 mb-5">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded-xl bg-[#246BFD]/15 text-[#246BFD] flex items-center justify-center font-bold">
                                        <i class="fa-solid fa-server"></i>
                                    </div>
                                    <div>
                                        <h3 class="text-base font-bold text-white">SMTP Gateway Parameters</h3>
                                        <p class="text-xs text-[#8F9CAE]">Configure the mail transport host, port, encryption protocol, and credentials.</p>
                                    </div>
                                </div>
                                <span class="px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[11px] font-semibold flex items-center gap-1.5">
                                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                                    {settings.get('encryption', 'tls').upper()} Gateway
                                </span>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">SMTP Host *</label>
                                    <input type="text" name="smtp_host" required value="{html_lib.escape(settings.get('smtp_host', ''))}" placeholder="smtp.mailgun.org"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">SMTP Port *</label>
                                    <input type="number" name="smtp_port" required value="{settings.get('smtp_port', 587)}" placeholder="587"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">SMTP Username *</label>
                                    <input type="text" name="smtp_username" required value="{html_lib.escape(settings.get('smtp_username', ''))}" placeholder="postmaster@domain.com"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">SMTP Password / Secret</label>
                                    <div class="relative">
                                        <input type="password" id="smtp_password" name="smtp_password" placeholder="••••••••••••"
                                            class="w-full pl-3.5 pr-10 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                        <button type="button" onclick="togglePassVisibility('smtp_password', this)" class="absolute inset-y-0 right-0 pr-3 flex items-center text-[#8F9CAE] hover:text-white">
                                            <i class="fa-regular fa-eye text-xs"></i>
                                        </button>
                                    </div>
                                    <p class="text-[10px] text-[#737D90] mt-1">Leave blank to retain currently saved password.</p>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Encryption Protocol *</label>
                                    <select name="encryption" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                        <option value="tls" {'selected' if settings.get('encryption') == 'tls' else ''}>STARTTLS (Standard - Port 587)</option>
                                        <option value="ssl" {'selected' if settings.get('encryption') == 'ssl' else ''}>SSL / TLS (Direct - Port 465)</option>
                                        <option value="none" {'selected' if settings.get('encryption') == 'none' else ''}>None / Unencrypted (Local Testing)</option>
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Sender Name *</label>
                                    <input type="text" name="from_name" required value="{html_lib.escape(settings.get('from_name', 'Alliance Bank Operations'))}" placeholder="Alliance Bank Operations"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div class="md:col-span-2">
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Sender Email Address *</label>
                                    <input type="email" name="from_address" required value="{html_lib.escape(settings.get('from_address', 'notifications@bnkfx.com'))}" placeholder="notifications@bnkfx.com"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>
                            </div>
                        </div>

                        <!-- Email Verification Policy Card -->
                        <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                            <div class="flex items-center justify-between border-b border-[#292E38] pb-4 mb-5">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded-xl bg-[#8054F6]/15 text-[#8054F6] flex items-center justify-center font-bold">
                                        <i class="fa-solid fa-user-shield"></i>
                                    </div>
                                    <div>
                                        <h3 class="text-base font-bold text-white">Identity & Verification Policy</h3>
                                        <p class="text-xs text-[#8F9CAE]">Enforce customer email confirmation before granting uninhibited banking transactions.</p>
                                    </div>
                                </div>
                            </div>

                            <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                                <div class="pr-4">
                                    <div class="text-sm font-semibold text-white">Require Email Verification on Registration</div>
                                    <div class="text-xs text-[#8F9CAE] mt-0.5">When enabled, newly registered users must confirm their email address via a secure token link before initiating external withdrawals or issuing high-tier cards.</div>
                                </div>
                                <label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
                                    <input type="checkbox" name="require_email_verification" value="1" {require_verif_checked} class="sr-only peer">
                                    <div class="w-11 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                </label>
                            </div>
                        </div>

                        <!-- Individual Notification Triggers -->
                        <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                            <div class="flex items-center justify-between border-b border-[#292E38] pb-4 mb-5">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded-xl bg-[#F5B942]/15 text-[#F5B942] flex items-center justify-center font-bold">
                                        <i class="fa-solid fa-sliders"></i>
                                    </div>
                                    <div>
                                        <h3 class="text-base font-bold text-white">Automated Notification Matrix</h3>
                                        <p class="text-xs text-[#8F9CAE]">Enable or disable individual notification channels based on compliance and operational requirements.</p>
                                    </div>
                                </div>
                            </div>

                            <div class="space-y-3">
                                {triggers_html}
                            </div>
                        </div>

                        <div class="flex justify-end pt-2">
                            <button type="submit" class="px-6 py-3 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/30 transition-all flex items-center gap-2">
                                <i class="fa-solid fa-floppy-disk"></i>
                                <span>Save Email Configuration</span>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Right Col: Live Diagnostic Tool & Information -->
                <div class="space-y-6">
                    <!-- Live SMTP Diagnostic Card -->
                    <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                        <div class="flex items-center gap-3 border-b border-[#292E38] pb-4 mb-4">
                            <div class="w-9 h-9 rounded-xl bg-[#20C997]/15 text-[#20C997] flex items-center justify-center font-bold">
                                <i class="fa-solid fa-paper-plane"></i>
                            </div>
                            <div>
                                <h3 class="text-base font-bold text-white">SMTP Diagnostic Tool</h3>
                                <p class="text-xs text-[#8F9CAE]">Send a live test email to verify gateway connectivity.</p>
                            </div>
                        </div>

                        <form id="test-email-form" onsubmit="sendDiagnosticTest(event)" class="space-y-4">
                            <div>
                                <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Recipient Test Address</label>
                                <input type="email" id="test-recipient-input" required value="{html_lib.escape(STATE.get('user', {}).get('email', 'admin@bnkfx.com'))}" placeholder="admin@bnkfx.com"
                                    class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                            </div>

                            <button type="submit" id="test-submit-btn" class="w-full py-2.5 px-4 rounded-xl bg-[#20C997] hover:bg-emerald-600 text-slate-950 font-bold text-xs tracking-wide uppercase transition-all shadow-md shadow-emerald-500/20 flex items-center justify-center gap-2">
                                <i class="fa-solid fa-bolt"></i>
                                <span>Send Test Email</span>
                            </button>
                        </form>

                        <!-- Diagnostic Console Output -->
                        <div id="diagnostic-console" class="mt-5 p-4 rounded-xl bg-[#0E1219] border border-[#292E38] text-xs font-mono text-[#8F9CAE] space-y-2">
                            <div class="text-[10px] uppercase font-bold text-[#737D90] tracking-wider border-b border-[#202634] pb-1 flex items-center justify-between">
                                <span>Diagnostic Monitor</span>
                                <span id="diag-status" class="text-emerald-400">Ready</span>
                            </div>
                            <div id="diag-log" class="space-y-1 text-[11px] max-h-48 overflow-y-auto">
                                <div>[SYS] Mail gateway idle. Ready to test socket relay.</div>
                            </div>
                        </div>
                    </div>

                    <!-- Security & Compliance Guidelines Card -->
                    <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-xl">
                        <div class="flex items-center gap-3 border-b border-[#292E38] pb-4 mb-4">
                            <div class="w-9 h-9 rounded-xl bg-[#F05D6C]/15 text-[#F05D6C] flex items-center justify-center font-bold">
                                <i class="fa-solid fa-shield-halved"></i>
                            </div>
                            <div>
                                <h3 class="text-base font-bold text-white">Security Architecture</h3>
                                <p class="text-xs text-[#8F9CAE]">Financial decoupling & credential protection.</p>
                            </div>
                        </div>

                        <ul class="space-y-3 text-xs text-[#8F9CAE]">
                            <li class="flex items-start gap-2.5">
                                <i class="fa-solid fa-check text-emerald-400 mt-0.5"></i>
                                <span><strong>Financial Decoupling:</strong> Transaction ledger updates are executed first. Mail delivery exceptions never reverse completed monetary transfers.</span>
                            </li>
                            <li class="flex items-start gap-2.5">
                                <i class="fa-solid fa-check text-emerald-400 mt-0.5"></i>
                                <span><strong>Deduplication Guard:</strong> Unique idempotency keys prevent duplicate email dispatch on retries or repeated webhook triggers.</span>
                            </li>
                            <li class="flex items-start gap-2.5">
                                <i class="fa-solid fa-check text-emerald-400 mt-0.5"></i>
                                <span><strong>Data Masking:</strong> Sensitive authentication passwords and full PAN card numbers are strictly stripped from outgoing templates.</span>
                            </li>
                            <li class="flex items-start gap-2.5">
                                <i class="fa-solid fa-check text-emerald-400 mt-0.5"></i>
                                <span><strong>Audit Trail:</strong> All SMTP credential modifications and test events are timestamped in the administrative security audit log.</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </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 sendDiagnosticTest(e) {{
            e.preventDefault();
            const btn = document.getElementById('test-submit-btn');
            const input = document.getElementById('test-recipient-input');
            const logBox = document.getElementById('diag-log');
            const statusBadge = document.getElementById('diag-status');

            const recipient = input.value.trim();
            if (!recipient) return;

            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i><span>Dispatched Socket Relay...</span>';
            statusBadge.textContent = 'Transmitting...';
            statusBadge.className = 'text-amber-400';

            const startTime = performance.now();
            logBox.innerHTML += `<div>[${{new Date().toLocaleTimeString()}}] Connecting to SMTP gateway for ${{recipient}}...</div>`;

            try {{
                const res = await fetch('/admin/settings/email/test', {{
                    method: 'POST',
                    headers: {{ 'Content-Type': 'application/json', 'Accept': 'application/json' }},
                    body: JSON.stringify({{ recipient_email: recipient }})
                }});
                const data = await res.json();
                const latency = Math.round(performance.now() - startTime);

                if (data.success) {{
                    statusBadge.textContent = 'Success (' + latency + 'ms)';
                    statusBadge.className = 'text-emerald-400 font-bold';
                    logBox.innerHTML += `<div class="text-emerald-400">[${{new Date().toLocaleTimeString()}}] &check; ${{data.message}} (Log #${{data.log_id || 'N/A'}}) in ${{latency}}ms</div>`;
                }} else {{
                    statusBadge.textContent = 'Failed';
                    statusBadge.className = 'text-red-400 font-bold';
                    logBox.innerHTML += `<div class="text-red-400">[${{new Date().toLocaleTimeString()}}] &cross; ${{data.message || 'Diagnostic transport error.'}}</div>`;
                }}
            }} catch (err) {{
                statusBadge.textContent = 'Error';
                statusBadge.className = 'text-red-400 font-bold';
                logBox.innerHTML += `<div class="text-red-400">[${{new Date().toLocaleTimeString()}}] Connection error: ${{err.message}}</div>`;
            }} finally {{
                btn.disabled = false;
                btn.innerHTML = '<i class="fa-solid fa-bolt"></i><span>Send Test Email</span>';
                logBox.scrollTop = logBox.scrollHeight;
            }}
        }}
        </script>
        '''
        html = build_admin_layout(body, "Email Settings | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 11. Email Delivery Logs Admin View
    if path == "/admin/email-logs":
        email_logs = list(STATE.get("email_logs", []))
        email_logs.reverse()  # Newest first

        total_count = len(email_logs)
        sent_count = sum(1 for e in email_logs if e.get("status") in ["sent", "delivered"])
        failed_count = sum(1 for e in email_logs if e.get("status") == "failed")
        queued_count = sum(1 for e in email_logs if e.get("status") == "queued")

        query = urllib.parse.parse_qs(parsed.query)
        curr_status = query.get("status", ["all"])[0]
        curr_template = query.get("template", ["all"])[0]
        search_q = query.get("q", [""])[0].lower().strip()

        filtered_logs = email_logs
        if curr_status != "all":
            if curr_status == "sent":
                filtered_logs = [e for e in filtered_logs if e.get("status") in ["sent", "delivered"]]
            else:
                filtered_logs = [e for e in filtered_logs if e.get("status") == curr_status]

        if curr_template != "all":
            filtered_logs = [e for e in filtered_logs if e.get("template") == curr_template]

        if search_q:
            filtered_logs = [e for e in filtered_logs if search_q in e.get("recipient", "").lower() or search_q in e.get("subject", "").lower() or search_q in e.get("template", "").lower()]

        rows_html = ""
        for log in filtered_logs:
            log_id = log.get("id", 0)
            status = log.get("status", "sent")
            template = log.get("template", "default")
            recipient = html_lib.escape(log.get("recipient", "N/A"))
            subject = html_lib.escape(log.get("subject", "Notification"))
            created_at = log.get("created_at", "N/A")
            error_msg = log.get("error_message") or ""

            if status in ["sent", "delivered"]:
                status_badge = '<span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Sent</span>'
            elif status == "failed":
                status_badge = '<span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-500/10 text-red-400 border border-red-500/20"><span class="w-1.5 h-1.5 rounded-full bg-red-400"></span>Failed</span>'
            else:
                status_badge = '<span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>Queued</span>'

            # Template badge color
            tpl_colors = {
                "welcome": "bg-blue-500/15 text-blue-400 border-blue-500/30",
                "email_verification": "bg-purple-500/15 text-purple-400 border-purple-500/30",
                "transaction": "bg-emerald-500/15 text-emerald-400 border-emerald-500/30",
                "security_alert": "bg-amber-500/15 text-amber-400 border-amber-500/30",
                "password_reset": "bg-indigo-500/15 text-indigo-400 border-indigo-500/30",
                "deposit_update": "bg-cyan-500/15 text-cyan-400 border-cyan-500/30",
                "card_update": "bg-pink-500/15 text-pink-400 border-pink-500/30",
                "test": "bg-gray-500/15 text-gray-300 border-gray-500/30"
            }
            tpl_class = tpl_colors.get(template, "bg-gray-500/15 text-gray-300 border-gray-500/30")
            template_badge = f'<span class="inline-block px-2.5 py-0.5 rounded-md text-[11px] font-semibold uppercase tracking-wider border {tpl_class}">{template.replace("_", " ")}</span>'

            # Metadata JSON string for inspection
            meta_json = html_lib.escape(json.dumps(log.get("metadata", {}), indent=2))
            error_display = f'<div class="text-[10px] text-red-400 font-mono mt-0.5 truncate max-w-xs">{html_lib.escape(error_msg)}</div>' if error_msg else ''

            rows_html += f'''
            <tr class="border-b border-[#292E38]/50 hover:bg-[#12151B]/60 transition-colors">
                <td class="py-3.5 px-4 font-mono text-xs text-[#8F9CAE]">#{log_id}</td>
                <td class="py-3.5 px-4 font-mono text-xs text-[#9CA6BA] whitespace-nowrap">{created_at}</td>
                <td class="py-3.5 px-4">
                    <div class="text-sm font-semibold text-white">{recipient}</div>
                    {f'<div class="text-[10px] text-[#737D90]">User ID: {log.get("user_id")}</div>' if log.get("user_id") else ''}
                </td>
                <td class="py-3.5 px-4">
                    <div class="text-sm font-medium text-white max-w-md truncate">{subject}</div>
                    {error_display}
                </td>
                <td class="py-3.5 px-4 whitespace-nowrap">{template_badge}</td>
                <td class="py-3.5 px-4 whitespace-nowrap">{status_badge}</td>
                <td class="py-3.5 px-4 text-right whitespace-nowrap">
                    <button type="button" onclick="openPayloadModal({log_id})" class="px-2.5 py-1 rounded-lg bg-[#202634] hover:bg-[#282E3E] text-xs font-semibold text-[#8F9CAE] hover:text-white transition-all">
                        <i class="fa-solid fa-code mr-1 text-[#246BFD]"></i> Payload
                    </button>
                </td>
            </tr>
            '''

        # JSON lookup dictionary for inspection modal
        logs_json_lookup = html_lib.escape(json.dumps({l["id"]: l for l in email_logs}))

        body = f'''
        <div class="max-w-7xl mx-auto space-y-6">
            <!-- Header -->
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <div class="flex items-center gap-2 text-xs text-[#8F9CAE] mb-1">
                        <a href="/admin" class="hover:text-white">Admin</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <a href="/admin/settings/email" class="hover:text-white">Email Settings</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <span class="text-white font-medium">Delivery Logs</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Email Delivery Logs</h1>
                    <p class="text-xs text-[#8F9CAE] mt-1">Audit outgoing transactional email payloads, transmission timestamps, and gateway error messages.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/admin/settings/email" class="px-4 py-2 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white text-xs font-semibold flex items-center gap-2 transition-all shadow-md shadow-blue-600/30">
                        <i class="fa-solid fa-gear"></i>
                        <span>Email Gateway Settings</span>
                    </a>
                </div>
            </div>

            <!-- KPI Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-xs text-[#8F9CAE] font-medium mb-1">Total Logs Recorded</div>
                    <div class="text-2xl font-bold text-white font-mono">{total_count}</div>
                    <div class="text-[11px] text-[#737D90] mt-1">Audit log entries</div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-xs text-[#8F9CAE] font-medium mb-1">Delivered Successfully</div>
                    <div class="text-2xl font-bold text-emerald-400 font-mono">{sent_count}</div>
                    <div class="text-[11px] text-emerald-400/80 mt-1">Sent without error</div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-xs text-[#8F9CAE] font-medium mb-1">Delivery Failures</div>
                    <div class="text-2xl font-bold text-red-400 font-mono">{failed_count}</div>
                    <div class="text-[11px] text-red-400/80 mt-1">Requires inspection</div>
                </div>

                <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                    <div class="text-xs text-[#8F9CAE] font-medium mb-1">Queued In Pipeline</div>
                    <div class="text-2xl font-bold text-amber-400 font-mono">{queued_count}</div>
                    <div class="text-[11px] text-amber-400/80 mt-1">Awaiting relay</div>
                </div>
            </div>

            <!-- Filter Controls -->
            <div class="p-4 rounded-2xl bg-[#171A21] border border-[#292E38] flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="flex flex-wrap items-center gap-2">
                    <a href="/admin/email-logs?status=all&template={curr_template}" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-[#246BFD] text-white' if curr_status == 'all' else 'text-[#8F9CAE] hover:text-white bg-[#12151B]'}">
                        All ({total_count})
                    </a>
                    <a href="/admin/email-logs?status=sent&template={curr_template}" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-emerald-600 text-white' if curr_status == 'sent' else 'text-[#8F9CAE] hover:text-white bg-[#12151B]'}">
                        Sent ({sent_count})
                    </a>
                    <a href="/admin/email-logs?status=failed&template={curr_template}" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all {'bg-red-600 text-white' if curr_status == 'failed' else 'text-[#8F9CAE] hover:text-white bg-[#12151B]'}">
                        Failed ({failed_count})
                    </a>
                </div>

                <form method="GET" action="/admin/email-logs" class="flex items-center gap-2">
                    <input type="hidden" name="status" value="{curr_status}">
                    <select name="template" onchange="this.form.submit()" class="px-3 py-1.5 rounded-lg bg-[#12151B] border border-[#292E38] text-xs text-white focus:outline-none focus:border-[#246BFD]">
                        <option value="all" {'selected' if curr_template == 'all' else ''}>All Templates</option>
                        <option value="welcome" {'selected' if curr_template == 'welcome' else ''}>Welcome</option>
                        <option value="email_verification" {'selected' if curr_template == 'email_verification' else ''}>Email Verification</option>
                        <option value="transaction" {'selected' if curr_template == 'transaction' else ''}>Transaction</option>
                        <option value="security_alert" {'selected' if curr_template == 'security_alert' else ''}>Security Alert</option>
                        <option value="password_reset" {'selected' if curr_template == 'password_reset' else ''}>Password Reset</option>
                        <option value="deposit_update" {'selected' if curr_template == 'deposit_update' else ''}>Deposit Update</option>
                        <option value="card_update" {'selected' if curr_template == 'card_update' else ''}>Card Update</option>
                        <option value="test" {'selected' if curr_template == 'test' else ''}>SMTP Test</option>
                    </select>
                    <div class="relative">
                        <input type="text" name="q" value="{html_lib.escape(search_q)}" placeholder="Search recipient or subject..."
                            class="pl-8 pr-3 py-1.5 rounded-lg bg-[#12151B] border border-[#292E38] text-xs text-white focus:outline-none focus:border-[#246BFD] w-48 sm:w-64">
                        <i class="fa-solid fa-magnifying-glass absolute left-2.5 top-2.5 text-[11px] text-[#737D90]"></i>
                    </div>
                    {f'<a href="/admin/email-logs" class="text-xs text-[#8F9CAE] hover:text-white px-1">Clear</a>' if search_q or curr_status != "all" or curr_template != "all" else ''}
                </form>
            </div>

            <!-- Logs Table -->
            <div class="rounded-2xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-[#12151B] border-b border-[#292E38] text-[11px] font-bold uppercase tracking-wider text-[#8F9CAE]">
                                <th class="py-3 px-4">Log ID</th>
                                <th class="py-3 px-4">Timestamp</th>
                                <th class="py-3 px-4">Recipient</th>
                                <th class="py-3 px-4">Subject</th>
                                <th class="py-3 px-4">Template</th>
                                <th class="py-3 px-4">Delivery Status</th>
                                <th class="py-3 px-4 text-right">Details</th>
                            </tr>
                        </thead>
                        <tbody>
                            {rows_html if rows_html else '<tr><td colspan="7" class="py-12 text-center text-[#737D90]"><i class="fa-solid fa-inbox text-2xl mb-2 text-[#246BFD]"></i><div>No email delivery logs match the selected filter criteria.</div></td></tr>'}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payload Inspection Modal -->
        <div id="payload-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
            <div class="w-full max-w-2xl bg-[#161A22] border border-[#282E3E] rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]">
                <div class="px-6 py-4 border-b border-[#282E3E] flex items-center justify-between bg-[#12151B]">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-[#246BFD]/20 text-[#246BFD] flex items-center justify-center font-bold">
                            <i class="fa-solid fa-code text-sm"></i>
                        </div>
                        <h3 class="text-base font-bold text-white" id="modal-title">Email Payload Details</h3>
                    </div>
                    <button type="button" onclick="closePayloadModal()" class="text-[#8F9CAE] hover:text-white p-1">
                        <i class="fa-solid fa-xmark text-lg"></i>
                    </button>
                </div>

                <div class="p-6 overflow-y-auto space-y-4">
                    <div class="grid grid-cols-2 gap-3 text-xs bg-[#0E1219] p-4 rounded-xl border border-[#282E3E]">
                        <div><span class="text-[#8F9CAE]">Recipient:</span> <span id="modal-recipient" class="font-semibold text-white ml-1"></span></div>
                        <div><span class="text-[#8F9CAE]">Template:</span> <span id="modal-template" class="font-semibold text-[#246BFD] ml-1 uppercase"></span></div>
                        <div><span class="text-[#8F9CAE]">Status:</span> <span id="modal-status" class="ml-1"></span></div>
                        <div><span class="text-[#8F9CAE]">Recorded At:</span> <span id="modal-time" class="font-mono text-white ml-1"></span></div>
                    </div>

                    <div>
                        <div class="text-xs font-semibold text-[#8F9CAE] uppercase tracking-wider mb-1">Subject</div>
                        <div id="modal-subject" class="text-sm font-bold text-white p-3 rounded-lg bg-[#0E1219] border border-[#282E3E]"></div>
                    </div>

                    <div id="modal-error-box" class="hidden">
                        <div class="text-xs font-semibold text-red-400 uppercase tracking-wider mb-1">Error Message</div>
                        <div id="modal-error" class="text-xs text-red-300 font-mono p-3 rounded-lg bg-red-500/10 border border-red-500/30"></div>
                    </div>

                    <div>
                        <div class="text-xs font-semibold text-[#8F9CAE] uppercase tracking-wider mb-1">Metadata (Context JSON)</div>
                        <pre id="modal-metadata" class="text-xs font-mono text-emerald-400 p-4 rounded-xl bg-[#0B0E14] border border-[#282E3E] overflow-x-auto"></pre>
                    </div>
                </div>

                <div class="px-6 py-3 border-t border-[#282E3E] bg-[#12151B] flex justify-end">
                    <button type="button" onclick="closePayloadModal()" class="px-4 py-2 rounded-xl bg-[#202634] hover:bg-[#282E3E] text-white text-xs font-semibold transition-all">
                        Close
                    </button>
                </div>
            </div>
        </div>

        <script>
        const LOGS_DATA = {logs_json_lookup};

        function openPayloadModal(id) {{
            const log = LOGS_DATA[id];
            if (!log) return;

            document.getElementById('modal-title').textContent = 'Email Payload #' + id;
            document.getElementById('modal-recipient').textContent = log.recipient || 'N/A';
            document.getElementById('modal-template').textContent = (log.template || 'default').replace('_', ' ');
            document.getElementById('modal-status').innerHTML = (log.status === 'sent' || log.status === 'delivered') 
                ? '<span class="text-emerald-400 font-bold">Sent / Delivered</span>'
                : (log.status === 'failed' ? '<span class="text-red-400 font-bold">Failed</span>' : '<span class="text-amber-400 font-bold">Queued</span>');
            document.getElementById('modal-time').textContent = log.created_at || 'N/A';
            document.getElementById('modal-subject').textContent = log.subject || 'Notification';

            const errBox = document.getElementById('modal-error-box');
            if (log.error_message) {{
                errBox.classList.remove('hidden');
                document.getElementById('modal-error').textContent = log.error_message;
            }} else {{
                errBox.classList.add('hidden');
            }}

            document.getElementById('modal-metadata').textContent = JSON.stringify(log.metadata || {{}}, null, 2);
            document.getElementById('payload-modal').classList.remove('hidden');
        }}

        function closePayloadModal() {{
            document.getElementById('payload-modal').classList.add('hidden');
        }}
        </script>
        '''
        html = build_admin_layout(body, "Email Delivery Logs | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    # 12. Platform Settings Admin View (Super Admin Only)
    if path == "/admin/settings/platform":
        actor_user = STATE.get("user", {})
        is_sa = platform_settings_service.is_super_admin(actor_user)

        settings = platform_settings_service.get_platform_settings(STATE)
        query = urllib.parse.parse_qs(parsed.query)
        active_tab = query.get("tab", ["general"])[0]

        saved_banner = ""
        if "saved" in query:
            saved_banner = '''
            <div class="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm flex items-center justify-between shadow-lg">
                <div class="flex items-center gap-3">
                    <i class="fa-solid fa-circle-check text-xl text-emerald-400"></i>
                    <div>
                        <div class="font-bold">Platform Configuration Persisted</div>
                        <div class="text-xs text-emerald-400/80">Global brand identity and platform settings have been committed and propagated.</div>
                    </div>
                </div>
                <button type="button" onclick="this.parentElement.remove()" class="text-emerald-400/60 hover:text-emerald-400">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            '''

        if not is_sa:
            body = f'''
            <div class="max-w-4xl mx-auto py-12 text-center space-y-6">
                <div class="w-16 h-16 rounded-2xl bg-red-500/15 text-red-400 border border-red-500/30 flex items-center justify-center mx-auto text-3xl shadow-xl">
                    <i class="fa-solid fa-lock"></i>
                </div>
                <div class="space-y-2">
                    <h2 class="text-2xl font-bold text-white tracking-tight">Super Administrator Access Required</h2>
                    <p class="text-sm text-[#8F9CAE] max-w-lg mx-auto">
                        Global platform settings, corporate branding, visual tokens, and server-side maintenance mode can only be modified by accounts holding the <strong>Super Administrator</strong> role.
                    </p>
                </div>
                <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] inline-block text-xs text-[#737D90] font-mono">
                    Current Identity: {html_lib.escape(actor_user.get("email", "unknown"))} (Role: {html_lib.escape(actor_user.get("role", "admin"))})
                </div>
                <div>
                    <a href="/admin" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[#202634] hover:bg-[#282E3E] text-white text-xs font-semibold transition-all">
                        <i class="fa-solid fa-arrow-left"></i>
                        <span>Return to Overview</span>
                    </a>
                </div>
            </div>
            '''
            html = build_admin_layout(body, "Access Denied | Platform Settings", path)
            handler.wfile.write(html.encode('utf-8'))
            return True

        # Render Full 10-Tab Interface for Super Admin
        tab_list = [
            ("general", "General Settings", "fa-gear"),
            ("brand", "Brand Identity & Colors", "fa-palette"),
            ("contact", "Contact & Support", "fa-address-book"),
            ("social", "Social Media", "fa-share-nodes"),
            ("auth", "Auth & Registration", "fa-user-shield"),
            ("email", "Email Branding", "fa-envelope-open-text"),
            ("localization", "Localization", "fa-globe"),
            ("seo", "SEO & Metadata", "fa-magnifying-glass"),
            ("security", "Security & Access", "fa-lock"),
            ("legal", "Legal Pages", "fa-scale-balanced")
        ]

        tabs_nav_html = ""
        for t_id, t_name, t_icon in tab_list:
            is_active = (t_id == active_tab)
            classes = "bg-[#246BFD] text-white shadow-lg shadow-blue-600/30" if is_active else "text-[#8F9CAE] hover:text-white hover:bg-[#171A21]"
            tabs_nav_html += f'''
            <button type="button" onclick="switchSettingTab('{t_id}')" id="tab-btn-{t_id}" class="w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-semibold text-left transition-all {classes}">
                <i class="fa-solid {t_icon} w-4 text-center"></i>
                <span class="truncate">{t_name}</span>
            </button>
            '''

        social_links = settings.get("social_links", {})

        body = f'''
        <div class="max-w-7xl mx-auto space-y-6">
            <!-- Header -->
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <div class="flex items-center gap-2 text-xs text-[#8F9CAE] mb-1">
                        <a href="/admin" class="hover:text-white">Admin</a>
                        <i class="fa-solid fa-chevron-right text-[10px]"></i>
                        <span class="text-white font-medium">Platform Settings & Brand Identity</span>
                    </div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Platform Settings</h1>
                    <p class="text-xs text-[#8F9CAE] mt-1">Manage global website identity, logos, dynamic brand tokens, contact details, and maintenance controls.</p>
                </div>
                <div class="flex items-center gap-3">
                    <a href="/api/settings/public" target="_blank" class="px-3.5 py-2 rounded-xl bg-[#171A21] hover:bg-[#202634] text-xs font-semibold text-[#8F9CAE] hover:text-white border border-[#292E38] transition-all flex items-center gap-2">
                        <i class="fa-solid fa-code text-[#246BFD]"></i>
                        <span>Public JSON API</span>
                    </a>
                </div>
            </div>

            {saved_banner}

            <!-- Main Workspace: Vertical Navigation + Form Panels -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <!-- Sidebar Tabs Navigation -->
                <div class="md:col-span-1 space-y-1 bg-[#12151B] p-3 rounded-2xl border border-[#292E38] h-fit sticky top-20">
                    <div class="text-[10px] font-bold uppercase tracking-wider text-[#737D90] px-3 py-2">Configuration Groups</div>
                    {tabs_nav_html}
                </div>

                <!-- Form Panels Container -->
                <div class="md:col-span-3">
                    <form id="platform-settings-form" onsubmit="savePlatformSettings(event)" class="space-y-6">
                        <input type="hidden" id="active_tab_input" name="active_tab" value="{active_tab}">

                        <!-- 1. GENERAL SETTINGS TAB -->
                        <div id="tab-section-general" class="tab-panel {'block' if active_tab == 'general' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-gear text-[#246BFD]"></i>
                                    General Platform Configuration
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Core identification fields, platform names, default currency, and operational timezone.</p>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Platform Full Name *</label>
                                    <input type="text" name="platform_name" required value="{html_lib.escape(settings.get('platform_name', ''))}" placeholder="Alliance Bank"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                    <p class="text-[10px] text-[#737D90] mt-1">Reflected across user dashboards, login, register, and email titles.</p>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Short / Compact Name *</label>
                                    <input type="text" name="short_name" required value="{html_lib.escape(settings.get('short_name', ''))}" placeholder="Alliance"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div class="sm:col-span-2">
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Website Title Tag</label>
                                    <input type="text" name="site_title" value="{html_lib.escape(settings.get('site_title', ''))}" placeholder="Alliance Bank — Institutional & Retail Digital Banking"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div class="sm:col-span-2">
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Site Description</label>
                                    <textarea name="site_description" rows="2" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">{html_lib.escape(settings.get('site_description', ''))}</textarea>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Website URL</label>
                                    <input type="url" name="site_url" value="{html_lib.escape(settings.get('site_url', ''))}" placeholder="https://bnkfx.com"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Default Currency</label>
                                    <input type="text" name="default_currency" value="{html_lib.escape(settings.get('default_currency', 'USD'))}" placeholder="USD"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors uppercase font-mono">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Company Legal Name</label>
                                    <input type="text" name="company_name" value="{html_lib.escape(settings.get('company_name', ''))}" placeholder="Alliance Bank Corporation Inc."
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Corporate Address</label>
                                    <input type="text" name="company_address" value="{html_lib.escape(settings.get('company_address', ''))}" placeholder="One Financial Plaza, Suite 400, New York, NY"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>
                            </div>
                        </div>

                        <!-- 2. BRAND IDENTITY & COLORS TAB -->
                        <div id="tab-section-brand" class="tab-panel {'block' if active_tab == 'brand' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-palette text-[#246BFD]"></i>
                                    Visual Identity & Dynamic Color Tokens
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Configure global theme colors. Changes propagate instantly to buttons, links, active tabs, and badges.</p>
                            </div>

                            <!-- Live Visual Preview Box -->
                            <div class="p-5 rounded-2xl bg-[#0E1219] border border-[#292E38] space-y-3">
                                <div class="text-[11px] font-bold uppercase tracking-wider text-[#737D90] flex items-center justify-between">
                                    <span>Interactive Brand Tokens Live Preview</span>
                                    <span class="text-emerald-400 font-mono text-[10px]">Real-Time Rendering</span>
                                </div>
                                <div id="live-brand-preview" class="p-5 rounded-xl border flex flex-wrap items-center gap-4 transition-all"
                                     style="background-color: {settings.get('card_color', '#171A21')}; border-color: {settings.get('border_color', '#292E38')};">
                                    <button type="button" id="preview-btn-primary" class="px-4 py-2 rounded-xl text-xs font-bold text-white shadow-lg transition-all"
                                            style="background-color: {settings.get('primary_color', '#246BFD')};">
                                        Primary CTA Button
                                    </button>
                                    <span id="preview-badge-accent" class="px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider"
                                          style="background-color: rgba(32, 201, 151, 0.15); color: {settings.get('accent_color', '#20C997')}; border: 1px solid {settings.get('accent_color', '#20C997')}33;">
                                        Accent Badge
                                    </span>
                                    <span id="preview-text-pri" class="text-sm font-semibold" style="color: {settings.get('text_primary', '#F8FAFC')};">
                                        Primary Text Heading
                                    </span>
                                    <a href="javascript:void(0)" id="preview-link" class="text-xs font-semibold underline" style="color: {settings.get('primary_color', '#246BFD')};">
                                        Active Link State
                                    </a>
                                </div>
                            </div>

                            <!-- Color Pickers Grid -->
                            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Primary Brand Color</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="primary_color_picker" value="{settings.get('primary_color', '#246BFD')}" onchange="syncColor('primary_color', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="primary_color" name="primary_color" value="{settings.get('primary_color', '#246BFD')}" oninput="syncColorPicker('primary_color', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Main buttons, focus states, and key highlights.</p>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Primary Hover Color</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="primary_hover_picker" value="{settings.get('primary_hover', '#1858D8')}" onchange="syncColor('primary_hover', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="primary_hover" name="primary_hover" value="{settings.get('primary_hover', '#1858D8')}" oninput="syncColorPicker('primary_hover', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Hover and pressed button feedback.</p>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Accent Color</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="accent_color_picker" value="{settings.get('accent_color', '#20C997')}" onchange="syncColor('accent_color', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="accent_color" name="accent_color" value="{settings.get('accent_color', '#20C997')}" oninput="syncColorPicker('accent_color', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Special badges, positive metrics, charts.</p>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Background Surface</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="bg_color_picker" value="{settings.get('bg_color', '#0B0D10')}" onchange="syncColor('bg_color', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="bg_color" name="bg_color" value="{settings.get('bg_color', '#0B0D10')}" oninput="syncColorPicker('bg_color', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Main page background foundation.</p>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Card & Container Color</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="card_color_picker" value="{settings.get('card_color', '#171A21')}" onchange="syncColor('card_color', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="card_color" name="card_color" value="{settings.get('card_color', '#171A21')}" oninput="syncColorPicker('card_color', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Elevated cards, modals, and panel tiles.</p>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] space-y-2">
                                    <label class="block text-xs font-semibold text-white">Border Accent</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" id="border_color_picker" value="{settings.get('border_color', '#292E38')}" onchange="syncColor('border_color', this.value)" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="border_color" name="border_color" value="{settings.get('border_color', '#292E38')}" oninput="syncColorPicker('border_color', this.value)" class="flex-1 px-3 py-1.5 rounded-lg bg-[#171A21] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                    <p class="text-[10px] text-[#737D90]">Dividers, card outlines, form borders.</p>
                                </div>
                            </div>

                            <!-- Logo Asset Inputs -->
                            <div class="border-t border-[#292E38] pt-5 space-y-4">
                                <h4 class="text-sm font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-image text-[#246BFD]"></i>
                                    Platform Logos & Favicons
                                </h4>
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Primary Logo URL</label>
                                        <input type="text" name="primary_logo_url" value="{html_lib.escape(settings.get('primary_logo_url', ''))}" placeholder="/assets/images/logo/logo-primary.svg"
                                            class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                    </div>

                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Compact / Icon Logo URL</label>
                                        <input type="text" name="icon_logo_url" value="{html_lib.escape(settings.get('icon_logo_url', ''))}" placeholder="/assets/images/logo/logo-icon.svg"
                                            class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                    </div>

                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Browser Favicon URL</label>
                                        <input type="text" name="favicon_url" value="{html_lib.escape(settings.get('favicon_url', ''))}" placeholder="/assets/images/logo/favicon.ico"
                                            class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                    </div>

                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Border Radius Preset</label>
                                        <select name="border_radius_preset" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                                            <option value="rounded-lg" {'selected' if settings.get('border_radius_preset') == 'rounded-lg' else ''}>Slight Curve (rounded-lg)</option>
                                            <option value="rounded-xl" {'selected' if settings.get('border_radius_preset') == 'rounded-xl' else ''}>Modern Curve (rounded-xl)</option>
                                            <option value="rounded-2xl" {'selected' if settings.get('border_radius_preset') == 'rounded-2xl' else ''}>Deep Curve (rounded-2xl - Default)</option>
                                            <option value="rounded-3xl" {'selected' if settings.get('border_radius_preset') == 'rounded-3xl' else ''}>Pill Curve (rounded-3xl)</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 3. CONTACT & SUPPORT TAB -->
                        <div id="tab-section-contact" class="tab-panel {'block' if active_tab == 'contact' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-address-book text-[#246BFD]"></i>
                                    Support Channels & Operations Desk
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Contact numbers, public support email, and help desk operating hours displayed across the website and footer.</p>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Customer Support Email *</label>
                                    <input type="email" name="support_email" required value="{html_lib.escape(settings.get('support_email', ''))}" placeholder="support@bnkfx.com"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Customer Support Phone</label>
                                    <input type="text" name="support_phone" value="{html_lib.escape(settings.get('support_phone', ''))}" placeholder="+1 (800) 555-0199"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Operating Hours</label>
                                    <input type="text" name="customer_service_hours" value="{html_lib.escape(settings.get('customer_service_hours', ''))}" placeholder="24/7/365 Global Operations Desk"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Help Center URL</label>
                                    <input type="text" name="help_center_url" value="{html_lib.escape(settings.get('help_center_url', ''))}" placeholder="/support"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD] transition-colors font-mono">
                                </div>
                            </div>
                        </div>

                        <!-- 4. SOCIAL MEDIA LINKS TAB -->
                        <div id="tab-section-social" class="tab-panel {'block' if active_tab == 'social' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-share-nodes text-[#246BFD]"></i>
                                    Official Social Media Profiles
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Toggle and configure links to verified social channels. Disabled profiles are hidden from user interfaces.</p>
                            </div>

                            <div class="space-y-3">
                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between gap-4">
                                    <div class="flex items-center gap-3 w-40">
                                        <i class="fa-brands fa-facebook text-blue-500 text-lg"></i>
                                        <span class="text-xs font-semibold text-white">Facebook</span>
                                    </div>
                                    <input type="url" name="social_facebook_url" value="{html_lib.escape(social_links.get('facebook', {}).get('url', ''))}" placeholder="https://facebook.com/..." class="flex-1 px-3 py-2 rounded-lg bg-[#171A21] border border-[#292E38] text-xs text-white">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="social_facebook_enabled" value="1" {'checked' if social_links.get('facebook', {}).get('enabled') else ''} class="sr-only peer">
                                        <div class="w-9 h-5 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between gap-4">
                                    <div class="flex items-center gap-3 w-40">
                                        <i class="fa-brands fa-x-twitter text-white text-lg"></i>
                                        <span class="text-xs font-semibold text-white">X / Twitter</span>
                                    </div>
                                    <input type="url" name="social_x_url" value="{html_lib.escape(social_links.get('x', {}).get('url', ''))}" placeholder="https://x.com/..." class="flex-1 px-3 py-2 rounded-lg bg-[#171A21] border border-[#292E38] text-xs text-white">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="social_x_enabled" value="1" {'checked' if social_links.get('x', {}).get('enabled') else ''} class="sr-only peer">
                                        <div class="w-9 h-5 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between gap-4">
                                    <div class="flex items-center gap-3 w-40">
                                        <i class="fa-brands fa-linkedin text-blue-400 text-lg"></i>
                                        <span class="text-xs font-semibold text-white">LinkedIn</span>
                                    </div>
                                    <input type="url" name="social_linkedin_url" value="{html_lib.escape(social_links.get('linkedin', {}).get('url', ''))}" placeholder="https://linkedin.com/company/..." class="flex-1 px-3 py-2 rounded-lg bg-[#171A21] border border-[#292E38] text-xs text-white">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="social_linkedin_enabled" value="1" {'checked' if social_links.get('linkedin', {}).get('enabled') else ''} class="sr-only peer">
                                        <div class="w-9 h-5 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="p-3.5 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between gap-4">
                                    <div class="flex items-center gap-3 w-40">
                                        <i class="fa-brands fa-telegram text-sky-400 text-lg"></i>
                                        <span class="text-xs font-semibold text-white">Telegram</span>
                                    </div>
                                    <input type="url" name="social_telegram_url" value="{html_lib.escape(social_links.get('telegram', {}).get('url', ''))}" placeholder="https://t.me/..." class="flex-1 px-3 py-2 rounded-lg bg-[#171A21] border border-[#292E38] text-xs text-white">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="social_telegram_enabled" value="1" {'checked' if social_links.get('telegram', {}).get('enabled') else ''} class="sr-only peer">
                                        <div class="w-9 h-5 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- 5. AUTHENTICATION & REGISTRATION TAB -->
                        <div id="tab-section-auth" class="tab-panel {'block' if active_tab == 'auth' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-user-shield text-[#246BFD]"></i>
                                    Authentication & Registration Security
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Configure sign-up access controls, password complexity rules, and session lifecycle policies.</p>
                            </div>

                            <div class="space-y-4">
                                <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                                    <div>
                                        <div class="text-sm font-semibold text-white">Allow Public Customer Registrations</div>
                                        <div class="text-xs text-[#8F9CAE]">When disabled, new users cannot register accounts via the public portal.</div>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="allow_registrations" value="1" {'checked' if settings.get('allow_registrations', True) else ''} class="sr-only peer">
                                        <div class="w-11 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                                    <div>
                                        <div class="text-sm font-semibold text-white">Require Email Verification</div>
                                        <div class="text-xs text-[#8F9CAE]">Enforces activation token confirmation before permitting high-tier transactions.</div>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="require_email_verification" value="1" {'checked' if settings.get('require_email_verification', True) else ''} class="sr-only peer">
                                        <div class="w-11 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="p-4 rounded-xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                                    <div>
                                        <div class="text-sm font-semibold text-white">Allow Password Reset Recovery</div>
                                        <div class="text-xs text-[#8F9CAE]">Enables self-service password reset dispatch via single-use tokens.</div>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="allow_password_reset" value="1" {'checked' if settings.get('allow_password_reset', True) else ''} class="sr-only peer">
                                        <div class="w-11 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#246BFD]"></div>
                                    </label>
                                </div>

                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Session Inactivity Timeout (Minutes)</label>
                                        <input type="number" name="session_timeout_minutes" min="5" max="1440" value="{settings.get('session_timeout_minutes', 120)}"
                                            class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                    </div>
                                    <div>
                                        <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Minimum Password Length</label>
                                        <input type="number" name="min_password_length" min="6" max="64" value="{settings.get('min_password_length', 8)}"
                                            class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 6. EMAIL BRANDING TAB -->
                        <div id="tab-section-email" class="tab-panel {'block' if active_tab == 'email' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-envelope-open-text text-[#246BFD]"></i>
                                    Email Template Branding
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Customize display signatures, accent colors, and footer notices across all transactional notifications.</p>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Email Sender Display Name</label>
                                    <input type="text" name="email_sender_name" value="{html_lib.escape(settings.get('email_sender_name', ''))}" placeholder="Alliance Bank Operations Desk"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Email Accent Color</label>
                                    <div class="flex items-center gap-2">
                                        <input type="color" value="{settings.get('email_accent_color', '#246BFD')}" onchange="document.getElementById('email_accent_color').value=this.value" class="w-9 h-9 rounded-lg border-0 bg-transparent cursor-pointer">
                                        <input type="text" id="email_accent_color" name="email_accent_color" value="{settings.get('email_accent_color', '#246BFD')}" class="flex-1 px-3 py-1.5 rounded-lg bg-[#12151B] border border-[#292E38] text-xs font-mono text-white">
                                    </div>
                                </div>

                                <div class="sm:col-span-2">
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Email Footer Legal Disclaimer</label>
                                    <textarea name="email_footer_text" rows="2" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">{html_lib.escape(settings.get('email_footer_text', ''))}</textarea>
                                </div>
                            </div>
                        </div>

                        <!-- 7. LOCALIZATION TAB -->
                        <div id="tab-section-localization" class="tab-panel {'block' if active_tab == 'localization' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-globe text-[#246BFD]"></i>
                                    Localization & Formatting Preferences
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Default timezone, date conventions, and supported regional currencies.</p>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Default Timezone</label>
                                    <select name="default_timezone" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                        <option value="UTC" {'selected' if settings.get('default_timezone') == 'UTC' else ''}>UTC (Coordinated Universal Time)</option>
                                        <option value="America/New_York" {'selected' if settings.get('default_timezone') == 'America/New_York' else ''}>America/New_York (EST/EDT)</option>
                                        <option value="Europe/London" {'selected' if settings.get('default_timezone') == 'Europe/London' else ''}>Europe/London (GMT/BST)</option>
                                        <option value="Asia/Tokyo" {'selected' if settings.get('default_timezone') == 'Asia/Tokyo' else ''}>Asia/Tokyo (JST)</option>
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Date Display Format</label>
                                    <select name="date_format" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                        <option value="Y-m-d" {'selected' if settings.get('date_format') == 'Y-m-d' else ''}>YYYY-MM-DD (2026-10-31)</option>
                                        <option value="M d, Y" {'selected' if settings.get('date_format') == 'M d, Y' else ''}>Mon DD, YYYY (Oct 31, 2026)</option>
                                        <option value="d/m/Y" {'selected' if settings.get('date_format') == 'd/m/Y' else ''}>DD/MM/YYYY (31/10/2026)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- 8. SEO & METADATA TAB -->
                        <div id="tab-section-seo" class="tab-panel {'block' if active_tab == 'seo' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-magnifying-glass text-[#246BFD]"></i>
                                    SEO & Public Search Metadata
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Control OpenGraph previews and search indexing headers for public landing pages. Authenticated customer pages remain strictly unindexed.</p>
                            </div>

                            <div class="space-y-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">OpenGraph Social Title</label>
                                    <input type="text" name="og_title" value="{html_lib.escape(settings.get('og_title', ''))}" placeholder="Alliance Bank — Institutional & Retail Digital Banking"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">OpenGraph Meta Description</label>
                                    <textarea name="og_description" rows="2" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">{html_lib.escape(settings.get('og_description', ''))}</textarea>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">SEO Search Keywords</label>
                                    <input type="text" name="seo_keywords" value="{html_lib.escape(settings.get('seo_keywords', ''))}" placeholder="online banking, crypto, virtual cards"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-sm focus:outline-none focus:border-[#246BFD]">
                                </div>
                            </div>
                        </div>

                        <!-- 9. SECURITY & ACCESS (MAINTENANCE MODE) TAB -->
                        <div id="tab-section-security" class="tab-panel {'block' if active_tab == 'security' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-lock text-[#246BFD]"></i>
                                    System Security & Maintenance Mode
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Server-enforced maintenance mode stops customer financial actions while preserving Super Admin management.</p>
                            </div>

                            <!-- Server-Enforced Maintenance Mode Card -->
                            <div class="p-5 rounded-2xl bg-gradient-to-r from-amber-500/10 via-amber-600/5 to-transparent border border-amber-500/30 space-y-4">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center gap-3">
                                        <div class="w-10 h-10 rounded-xl bg-amber-500/20 text-amber-400 flex items-center justify-center text-lg">
                                            <i class="fa-solid fa-triangle-exclamation"></i>
                                        </div>
                                        <div>
                                            <div class="text-sm font-bold text-white">Server-Enforced Maintenance Mode</div>
                                            <div class="text-xs text-[#8F9CAE]">Blocks ordinary users from accessing dashboards, transfers, or deposits. Administrators retain full access.</div>
                                        </div>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" id="maintenance_mode_checkbox" name="maintenance_mode" value="1" {'checked' if settings.get('maintenance_mode') else ''} onchange="confirmMaintenanceToggle(this)" class="sr-only peer">
                                        <div class="w-12 h-6 bg-[#202634] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-amber-500"></div>
                                    </label>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-amber-300 mb-1.5">Maintenance Banner Message</label>
                                    <textarea name="maintenance_mode_message" rows="2" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-amber-500/30 text-white text-xs focus:outline-none focus:border-amber-400">{html_lib.escape(settings.get('maintenance_mode_message', ''))}</textarea>
                                </div>
                            </div>
                        </div>

                        <!-- 10. LEGAL PAGES TAB -->
                        <div id="tab-section-legal" class="tab-panel {'block' if active_tab == 'legal' else 'hidden'} p-6 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-6">
                            <div class="border-b border-[#292E38] pb-4">
                                <h3 class="text-base font-bold text-white flex items-center gap-2">
                                    <i class="fa-solid fa-scale-balanced text-[#246BFD]"></i>
                                    Legal Pages & Compliance Content
                                </h3>
                                <p class="text-xs text-[#8F9CAE] mt-0.5">Content displayed on /terms, /privacy, /risk, and site footers.</p>
                            </div>

                            <div class="space-y-4">
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Terms of Service Content (/terms)</label>
                                    <textarea name="terms_of_service" rows="3" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-mono focus:outline-none focus:border-[#246BFD]">{html_lib.escape(settings.get('legal', {}).get('terms_of_service', ''))}</textarea>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Privacy Policy Content (/privacy)</label>
                                    <textarea name="privacy_policy" rows="3" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-mono focus:outline-none focus:border-[#246BFD]">{html_lib.escape(settings.get('legal', {}).get('privacy_policy', ''))}</textarea>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Risk Disclosure Notice (/risk)</label>
                                    <textarea name="risk_disclosure" rows="2" class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-mono focus:outline-none focus:border-[#246BFD]">{html_lib.escape(settings.get('legal', {}).get('risk_disclosure', ''))}</textarea>
                                </div>

                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Footer Copyright Line</label>
                                    <input type="text" name="copyright_text" value="{html_lib.escape(settings.get('legal', {}).get('copyright_text', ''))}"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs focus:outline-none focus:border-[#246BFD]">
                                </div>
                            </div>
                        </div>

                        <!-- Sticky Submit Bar -->
                        <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-between shadow-xl">
                            <div class="flex items-center gap-2 text-xs text-[#8F9CAE]">
                                <i class="fa-solid fa-shield-halved text-emerald-400"></i>
                                <span>Super Admin Authorization Active</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span id="save-status-indicator" class="text-xs text-[#8F9CAE] font-medium hidden">Saving...</span>
                                <button type="submit" id="save-settings-btn" class="px-6 py-2.5 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-xs uppercase tracking-wider transition-all shadow-lg shadow-blue-600/30 flex items-center gap-2">
                                    <i class="fa-solid fa-floppy-disk"></i>
                                    <span>Save Configuration</span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
        function switchSettingTab(tabId) {{
            document.querySelectorAll('.tab-panel').forEach(p => p.classList.add('hidden'));
            const target = document.getElementById('tab-section-' + tabId);
            if (target) target.classList.remove('hidden');

            document.querySelectorAll('[id^="tab-btn-"]').forEach(b => {{
                b.className = 'w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-semibold text-left transition-all text-[#8F9CAE] hover:text-white hover:bg-[#171A21]';
            }});
            const activeBtn = document.getElementById('tab-btn-' + tabId);
            if (activeBtn) {{
                activeBtn.className = 'w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-semibold text-left transition-all bg-[#246BFD] text-white shadow-lg shadow-blue-600/30';
            }}
            document.getElementById('active_tab_input').value = tabId;
        }}

        function syncColor(id, val) {{
            document.getElementById(id).value = val;
            updatePreviewColors();
        }}

        function syncColorPicker(id, val) {{
            if (/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(val)) {{
                document.getElementById(id + '_picker').value = val;
                updatePreviewColors();
            }}
        }}

        function updatePreviewColors() {{
            const pri = document.getElementById('primary_color').value;
            const acc = document.getElementById('accent_color').value;
            const card = document.getElementById('card_color').value;
            const border = document.getElementById('border_color').value;
            const text = document.getElementById('text_primary').value;

            const btn = document.getElementById('preview-btn-primary');
            if (btn) btn.style.backgroundColor = pri;

            const link = document.getElementById('preview-link');
            if (link) link.style.color = pri;

            const badge = document.getElementById('preview-badge-accent');
            if (badge) {{
                badge.style.color = acc;
                badge.style.borderColor = acc;
            }}

            const box = document.getElementById('live-brand-preview');
            if (box) {{
                box.style.backgroundColor = card;
                box.style.borderColor = border;
            }}
        }}

        function confirmMaintenanceToggle(cb) {{
            if (cb.checked) {{
                if (!confirm('Enable Maintenance Mode? Ordinary users will be immediately blocked from logging in or performing transactions. Super Admins retain full access.')) {{
                    cb.checked = false;
                }}
            }}
        }}

        async function savePlatformSettings(e) {{
            e.preventDefault();
            const form = e.target;
            const btn = document.getElementById('save-settings-btn');
            const indicator = document.getElementById('save-status-indicator');

            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i><span>Persisting...</span>';
            indicator.classList.remove('hidden');
            indicator.textContent = 'Persisting to runtime state...';
            indicator.className = 'text-xs text-amber-400 font-medium';

            const formData = new FormData(form);
            const dataObj = {{}};
            formData.forEach((val, key) => {{ dataObj[key] = val; }});

            try {{
                const res = await fetch('/admin/settings/platform', {{
                    method: 'POST',
                    headers: {{ 'Content-Type': 'application/json', 'Accept': 'application/json' }},
                    body: JSON.stringify(dataObj)
                }});
                const data = await res.json();
                if (data.success) {{
                    indicator.textContent = 'Saved successfully!';
                    indicator.className = 'text-xs text-emerald-400 font-bold';
                    setTimeout(() => {{ indicator.classList.add('hidden'); }}, 2500);
                }} else {{
                    alert('Error saving settings: ' + (data.error || 'Unknown error'));
                    indicator.textContent = 'Failed to save.';
                    indicator.className = 'text-xs text-red-400 font-bold';
                }}
            }} catch (err) {{
                alert('Connection error: ' + err.message);
                indicator.textContent = 'Connection error.';
                indicator.className = 'text-xs text-red-400 font-bold';
            }} finally {{
                btn.disabled = false;
                btn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i><span>Save Configuration</span>';
            }}
        }}
        </script>
        '''
        html = build_admin_layout(body, "Platform Settings | Bnkfx Admin", path)
        handler.wfile.write(html.encode('utf-8'))
        return True

    return False
