import { For, Show, createSignal, onMount } from "solid-js";
import { Portal } from "solid-js/web";
import { BTN_GHOST, BTN_ORANGE, BTN_PRIMARY, CARD, ORANGE, NAVY, PKG_CARD } from "~/components/DashboardShell";
import { PROFESSIONAL_ROLE_SET, ROLE_PREFIXES, type RoleKey } from "./RoleDashboardShared";
import { openPayuCheckout, submitPayuCheckout } from "~/lib/payu";

const API = "";

type Props = { roleKey: RoleKey; dashboardConfig?: Record<string, any> | null };

type Package = {
  id: string;
  name: string;
  role_key: string;
  package_type: string;
  tracecoins_amount: number;
  price: number;
  description?: string;
};

type Payment = {
  id: string;
  amount_inr: number;
  tracecoins_credited: number;
  status: string;
  created_at: string;
  package_name?: string;
};

type AiCreditPackage = {
  id: string;
  name: string;
  description?: string;
  credits: number;
  price_inr: number;
};

type AiUsageLog = {
  id: string;
  feature_code: string;
  model_alias: string;
  credits_charged: number;
  status: string;
  created_at: string;
};

type AiUsageSummary = {
  remaining_credits: number;
  remaining_daily_actions: number;
  daily_action_limit: number;
  plan_code: string;
  plan_name: string;
  monthly_credits_total: number;
  monthly_credits_used: number;
  purchased_credits_total: number;
  purchased_credits_used: number;
};

interface Hold {
  id: string;
  amount: number;
  reason: string;
  reference_id: string | null;
  status: string;
  expires_at: string | null;
  created_at: string;
}

type CheckoutState = {
  package: Package | null;
  aiCreditPackage: AiCreditPackage | null;
  orderId: string | null;
  step: "form" | "processing" | "success" | "error";
  error: string;
};

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

export default function CreditsPage(props: Props) {
  const [wallet, setWallet] = createSignal<any>(null);
  const [ledger, setLedger] = createSignal<any[]>([]);
  const [packages, setPackages] = createSignal<Package[]>([]);
  const [payments, setPayments] = createSignal<Payment[]>([]);
  const [aiPackages, setAiPackages] = createSignal<AiCreditPackage[]>([]);
  const [aiUsage, setAiUsage] = createSignal<AiUsageLog[]>([]);
  const [aiSummary, setAiSummary] = createSignal<AiUsageSummary | null>(null);
  const [holds, setHolds] = createSignal<Hold[]>([]);
  const [releaseBusyId, setReleaseBusyId] = createSignal("");
  const [lowBalanceWarning, setLowBalanceWarning] = createSignal(false);
  const [loading, setLoading] = createSignal(true);
  const [loadingPayments, setLoadingPayments] = createSignal(false);
  const [err, setErr] = createSignal("");
  const [msg, setMsg] = createSignal("");
  const [activeTab, setActiveTab] = createSignal<"overview" | "buy_credits" | "buy_ai_credits" | "transactions" | "usage_history" | "ai_usage" | "holds">("overview");

  const LOW_BALANCE_THRESHOLD = 50;

  // Checkout modal state
  const [checkout, setCheckout] = createSignal<CheckoutState>({
    package: null,
    aiCreditPackage: null,
    orderId: null,
    step: "form",
    error: "",
  });
  const isProfessional = () => PROFESSIONAL_ROLE_SET.has(props.roleKey);
  const prefix = () => ROLE_PREFIXES[props.roleKey];

  const pkgCardTheme = () => {
    const cfg = props.dashboardConfig;
    return {
      WHITE: cfg?.pkg_card?.white ?? PKG_CARD.WHITE,
      COIN_BG: cfg?.pkg_card?.coin_bg ?? PKG_CARD.COIN_BG,
      COIN_AVATAR_BG: cfg?.pkg_card?.coin_avatar_bg ?? PKG_CARD.COIN_AVATAR_BG,
      BEST_VALUE_BG: cfg?.pkg_card?.best_value_bg ?? PKG_CARD.BEST_VALUE_BG,
      BORDER_DEFAULT: cfg?.pkg_card?.border_default ?? PKG_CARD.BORDER_DEFAULT,
      TEXT_SECONDARY: cfg?.pkg_card?.text_secondary ?? PKG_CARD.TEXT_SECONDARY,
      TEXT_PRIMARY: cfg?.pkg_card?.text_primary ?? PKG_CARD.TEXT_PRIMARY,
      TEXT_ACCENT: cfg?.pkg_card?.text_accent ?? PKG_CARD.TEXT_ACCENT,
      TEXT_MUTED: cfg?.pkg_card?.text_muted ?? PKG_CARD.TEXT_MUTED,
      TEXT_SUCCESS: cfg?.pkg_card?.text_success ?? PKG_CARD.TEXT_SUCCESS,
      SHADOW_DEFAULT: cfg?.pkg_card?.shadow_default ?? PKG_CARD.SHADOW_DEFAULT,
      SHADOW_ACCENT: cfg?.pkg_card?.shadow_accent ?? PKG_CARD.SHADOW_ACCENT,
    };
  };

  const loadWalletData = async () => {
    if (!isProfessional()) return;
    try {
      const [walletRes, ledgerRes, holdsRes] = await Promise.all([
        apiFetch(`/api/${prefix()}/wallet/me`),
        apiFetch(`/api/${prefix()}/wallet/me/ledger?page=1&limit=20`),
        apiFetch(`/api/${prefix()}/wallet/me/holds`),
      ]);
      const walletJson = await walletRes.json().catch(() => ({}));
      const ledgerJson = await ledgerRes.json().catch(() => ({}));
      const holdsJson = await holdsRes.json().catch(() => ({}));
      if (walletRes.ok) {
        setWallet(walletJson);
        const available = Number(walletJson?.available ?? 0);
        setLowBalanceWarning(available < LOW_BALANCE_THRESHOLD);
      }
      if (ledgerRes.ok) setLedger(Array.isArray(ledgerJson?.data) ? ledgerJson.data : []);
      if (holdsRes.ok) {
        const all = Array.isArray(holdsJson?.data) ? holdsJson.data : [];
        setHolds(all.filter((h: Hold) => h.status === "ACTIVE"));
      }
    } catch {
      // non-blocking
    }
  };

  const releaseHold = async (holdId: string) => {
    if (!confirm("Release this hold? Your tracecoins will be returned to your available balance.")) return;
    setReleaseBusyId(holdId);
    try {
      const res = await apiFetch(`/api/${prefix()}/wallet/me/holds/${holdId}/release`, {
        method: "POST",
      });
      if (res.ok) {
        setMsg("Hold released. Tracecoins returned to your available balance.");
        await loadWalletData();
      } else {
        const data = await res.json().catch(() => ({}));
        setErr(data?.message || "Failed to release hold.");
      }
    } catch (e: any) {
      setErr(e?.message || "Failed to release hold.");
    } finally {
      setReleaseBusyId("");
    }
  };

  const loadPackages = async () => {
    try {
      const res = await apiFetch(`/api/packages`);
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        const allPkgs = Array.isArray(data?.data)
          ? data.data
          : Array.isArray(data?.packages)
            ? data.packages
            : [];
        const filtered = allPkgs
          .filter((p: any) => p.role_key === props.roleKey)
          .map((p: any) => ({
            id: p.id,
            name: p.name,
            role_key: p.role_key,
            package_type: p.package_type,
            tracecoins_amount: p.tracecoins_amount,
            price: p.price_inr,
            description: p.description,
          }));
        setPackages(filtered);
      }
    } catch {
      setPackages([]);
    }
  };

  const loadPayments = async () => {
    setLoadingPayments(true);
    try {
      const res = await apiFetch("/api/payments/invoices?page=1&limit=50");
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setPayments(Array.isArray(data?.data) ? data.data : []);
      } else {
        setPayments([]);
      }
    } catch {
      setPayments([]);
    } finally {
      setLoadingPayments(false);
    }
  };

  const loadAiPackages = async () => {
    try {
      const res = await apiFetch("/api/ai-credits");
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setAiPackages(
          Array.isArray(data?.packages)
            ? data.packages.map((p: any) => ({
                id: p.id,
                name: p.name,
                description: p.description,
                credits: p.credits,
                price_inr: p.price_inr,
              }))
            : []
        );
      }
    } catch {
      setAiPackages([]);
    }
  };

  const loadAiUsage = async () => {
    try {
      const [summaryRes, logsRes] = await Promise.all([
        apiFetch("/api/ai/usage/summary"),
        apiFetch("/api/ai/usage/logs"),
      ]);
      const summaryData = await summaryRes.json().catch(() => ({}));
      const logsData = await logsRes.json().catch(() => ({}));
      if (summaryRes.ok) {
        const p = summaryData.plan_details || summaryData.plan || {};
        setAiSummary({
          remaining_credits: p.remaining_credits ?? summaryData.monthly_remaining ?? 0,
          remaining_daily_actions: p.remaining_daily_actions ?? summaryData.daily_remaining ?? 0,
          daily_action_limit: p.daily_action_limit ?? summaryData.daily_limit ?? 0,
          plan_code: p.plan_code ?? summaryData.plan_code ?? "free",
          plan_name: p.plan_name ?? summaryData.plan ?? "Free",
          monthly_credits_total: p.monthly_credits_total ?? summaryData.monthly_limit ?? 0,
          monthly_credits_used: p.monthly_credits_used ?? summaryData.monthly_used ?? 0,
          purchased_credits_total: p.purchased_credits_total ?? 0,
          purchased_credits_used: p.purchased_credits_used ?? 0,
        });
      }
      if (logsRes.ok) {
        setAiUsage(Array.isArray(logsData?.logs) ? logsData.logs : []);
      }
    } catch {
      setAiUsage([]);
    }
  };

  const loadAllData = async () => {
    setLoading(true);
    setErr("");
    await Promise.all([
      loadWalletData(),
      loadPackages(),
      loadPayments(),
      loadAiPackages(),
      loadAiUsage(),
    ]);
    setLoading(false);
  };

  onMount(loadAllData);

  const openCheckout = (pkg: Package) => {
    setCheckout({ package: pkg, aiCreditPackage: null, orderId: null, step: "form", error: "" });
  };

  const openAiCreditCheckout = (pkg: AiCreditPackage) => {
    setCheckout({ package: null, aiCreditPackage: pkg, orderId: null, step: "form", error: "" });
  };

  const closeCheckout = () => {
    setCheckout({ package: null, aiCreditPackage: null, orderId: null, step: "form", error: "" });
  };

  const processAiCreditPayment = async (aiPkg: AiCreditPackage) => {
    setCheckout((c) => ({ ...c, step: "processing", error: "" }));

    try {
      const orderRes = await apiFetch("/api/ai-credits/order", {
        method: "POST",
        body: JSON.stringify({ package_id: aiPkg.id }),
      });
      const orderData = await orderRes.json().catch(() => ({}));

      if (!orderRes.ok) {
        setCheckout((c) => ({
          ...c,
          step: "error",
          error: orderData.error || orderData.message || "Failed to create order",
        }));
        return;
      }

      // Submit the order /api/ai-credits/order already created, rather than
      // going through openPayuCheckout (which would create a SECOND,
      // different order via /api/payments/create-order, using this order's
      // txnid as if it were a package_id -- wrong endpoint, wrong id, and
      // the resulting hash wouldn't match this order's key/txnid anyway).
      const paymentResult = await submitPayuCheckout({
        key: orderData.key,
        txnid: orderData.txnid,
        amount: orderData.amount,
        productinfo: orderData.productinfo,
        firstname: orderData.firstname,
        email: orderData.email,
        phone: orderData.phone,
        surl: orderData.surl,
        furl: orderData.furl,
        hash: orderData.hash,
        payu_base_url: orderData.payu_base_url,
        udf1: orderData.udf1,
        udf2: orderData.udf2,
      });

      const verifyRes = await apiFetch("/api/ai-credits/verify", {
        method: "POST",
        body: JSON.stringify({
          txnid: paymentResult.txnid,
          mihpayid: paymentResult.mihpayid,
          status: paymentResult.status,
          hash: paymentResult.hash,
          amount: paymentResult.amount,
          productinfo: paymentResult.productinfo,
          firstname: paymentResult.firstname,
          email: paymentResult.email,
          udf1: paymentResult.udf1,
          udf2: paymentResult.udf2,
        }),
      });
      const verifyData = await verifyRes.json().catch(() => ({}));

      if (verifyRes.ok && verifyData.verified) {
        setCheckout((c) => ({ ...c, step: "success", orderId: paymentResult.txnid }));
        setMsg(`Payment successful! ${verifyData.credits_added} AI credits have been added.`);
        loadAllData();
      } else {
        setCheckout((c) => ({
          ...c,
          step: "error",
          error: verifyData.error || "Payment verification failed",
        }));
      }
    } catch (e: any) {
      setCheckout((c) => ({
        ...c,
        step: "error",
        error: e.message || "Payment failed. Please try again.",
      }));
    }
  };

  const processPayment = async () => {
    const pkg = checkout().package;
    const aiPkg = checkout().aiCreditPackage;
    if (!pkg && !aiPkg) return;

    if (aiPkg) {
      await processAiCreditPayment(aiPkg);
      return;
    }

    if (!pkg) return;

    setCheckout((c) => ({ ...c, step: "processing", error: "" }));

    try {
      const orderRes = await apiFetch("/api/payments/create-order", {
        method: "POST",
        body: JSON.stringify({
          amount: pkg.price,
          currency: "INR",
          package_id: pkg.id,
        }),
      });
      const orderData = await orderRes.json().catch(() => ({}));

      if (!orderRes.ok) {
        setCheckout((c) => ({
          ...c,
          step: "error",
          error: orderData.error || orderData.message || "Failed to create order",
        }));
        return;
      }

      const paymentResult = await submitPayuCheckout({
        key: orderData.key,
        txnid: orderData.txnid || orderData.order_id,
        amount: orderData.amount,
        productinfo: orderData.productinfo,
        firstname: orderData.firstname,
        email: orderData.email,
        phone: orderData.phone || "",
        surl: orderData.surl,
        furl: orderData.furl,
        hash: orderData.hash,
        payu_base_url: orderData.payu_base_url,
        udf1: orderData.udf1,
        udf2: orderData.udf2,
      });

      const verifyRes = await apiFetch("/api/payments/verify", {
        method: "POST",
        body: JSON.stringify({
          txnid: paymentResult.txnid,
          mihpayid: paymentResult.mihpayid,
          status: paymentResult.status,
          hash: paymentResult.hash,
          amount: paymentResult.amount,
          productinfo: paymentResult.productinfo,
          firstname: paymentResult.firstname,
          email: paymentResult.email,
          phone: paymentResult.phone,
          udf1: paymentResult.udf1,
          udf2: paymentResult.udf2,
          udf3: paymentResult.udf3,
          udf4: paymentResult.udf4,
          udf5: paymentResult.udf5,
        }),
      });
      const verifyData = await verifyRes.json().catch(() => ({}));

      if (verifyRes.ok && verifyData.verified) {
        setCheckout((c) => ({ ...c, step: "success", orderId: paymentResult.txnid }));
        setMsg(
          `Payment successful! ${pkg.tracecoins_amount} Tracecoins have been added to your wallet.`
        );
        loadAllData();
      } else {
        setCheckout((c) => ({
          ...c,
          step: "error",
          error: verifyData.message || "Payment verification failed",
        }));
      }
    } catch (e: any) {
      setCheckout((c) => ({
        ...c,
        step: "error",
        error: e.message || "Payment failed. Please try again.",
      }));
    }
  };

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleString("en-IN");
    } catch {
      return dateStr;
    }
  };

  const formatCurrency = (amount: number | string) => {
    const num = typeof amount === "string" ? parseFloat(amount) : amount;
    if (isNaN(num)) return "₹—";
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 0,
    }).format(num);
  };

  const CheckoutModal = () => (
      <Show when={checkout().package || checkout().aiCreditPackage}>
        <Portal>
          <div
            style={{
              position: "fixed",
              inset: "0",
              background: "rgba(0,0,0,0.5)",
              display: "flex",
              "align-items": "center",
              "justify-content": "center",
              "z-index": "1000",
              padding: "20px",
            }}
            onClick={(e) => {
              if (e.target === e.currentTarget && checkout().step !== "processing") closeCheckout();
            }}
          >
            <div
              style={{
                background: "#fff",
                "border-radius": "16px",
                padding: "24px",
                "max-width": "420px",
                width: "100%",
                "box-shadow": "0 20px 60px rgba(0,0,0,0.2)",
              }}
            >
              {/* Header */}
              <div
                style={{
                  display: "flex",
                  "justify-content": "space-between",
                  "align-items": "center",
                  "margin-bottom": "20px",
                }}
              >
                <h3
                  style={{ margin: "0", "font-size": "18px", "font-weight": "700", color: "#111827" }}
                >
                  {checkout().step === "success"
                    ? "✓ Payment Successful"
                    : checkout().step === "error"
                      ? "Payment Failed"
                      : "Checkout"}
                </h3>
                <Show when={checkout().step !== "processing"}>
                  <button
                    onClick={closeCheckout}
                    style={{
                      background: "none",
                      border: "none",
                      cursor: "pointer",
                      "font-size": "24px",
                      color: "#9CA3AF",
                    }}
                  >
                    ×
                  </button>
                </Show>
              </div>

              {/* Package Summary */}
              <Show when={checkout().step !== "success"}>
                <div
                  style={{
                    background: "#F9FAFB",
                    "border-radius": "12px",
                    padding: "16px",
                    "margin-bottom": "20px",
                  }}
                >
                  <p style={{ margin: "0 0 8px", "font-size": "13px", color: "#6B7280" }}>Package</p>
                  <p
                    style={{
                      margin: "0 0 4px",
                      "font-size": "16px",
                      "font-weight": "700",
                      color: "#111827",
                    }}
                  >
                    {checkout().package ? checkout().package!.name : checkout().aiCreditPackage?.name}
                  </p>
                  <p
                    style={{
                      margin: "0",
                      "font-size": "24px",
                      "font-weight": "800",
                      color: "#FF5E13",
                    }}
                  >
                    {formatCurrency(checkout().package ? checkout().package!.price : checkout().aiCreditPackage!.price_inr)}
                  </p>
                  <p style={{ margin: "8px 0 0", "font-size": "14px", color: "#15803D" }}>
                    +{checkout().package ? `${checkout().package!.tracecoins_amount} Tracecoins` : `${checkout().aiCreditPackage!.credits} AI Credits`}
                  </p>
                </div>
              </Show>

              {/* Success State */}
              <Show when={checkout().step === "success"}>
                <div style={{ "text-align": "center", padding: "20px 0" }}>
                  <div style={{ "font-size": "48px", "margin-bottom": "16px" }}>🎉</div>
                  <p style={{ margin: "0 0 8px", "font-size": "16px", color: "#111827" }}>
                    Payment successful!
                  </p>
                  <p style={{ margin: "0 0 16px", "font-size": "14px", color: "#6B7280" }}>
                    {checkout().package ? `${checkout().package!.tracecoins_amount} Tracecoins` : `${checkout().aiCreditPackage!.credits} AI Credits`} have been credited to your account.
                  </p>
                  <p style={{ margin: "0", "font-size": "12px", color: "#9CA3AF" }}>
                    Order ID: {checkout().orderId}
                  </p>
                </div>
                <button
                  onClick={closeCheckout}
                  style={{ ...BTN_PRIMARY, width: "100%", "margin-top": "16px" }}
                >
                  Done
                </button>
              </Show>

              {/* Error State */}
              <Show when={checkout().step === "error"}>
                <div style={{ "text-align": "center", padding: "20px 0" }}>
                  <div style={{ "font-size": "48px", "margin-bottom": "16px" }}>❌</div>
                  <p style={{ margin: "0 0 16px", "font-size": "14px", color: "#B91C1C" }}>
                    {checkout().error || "Payment failed. Please try again."}
                  </p>
                </div>
                <div style={{ display: "flex", gap: "12px" }}>
                  <button
                    onClick={() => setCheckout((c) => ({ ...c, step: "form", error: "" }))}
                    style={{ ...BTN_GHOST, flex: "1" }}
                  >
                    Try Again
                  </button>
                  <button onClick={closeCheckout} style={{ ...BTN_PRIMARY, flex: "1" }}>
                    Cancel
                  </button>
                </div>
              </Show>

              {/* Processing State */}
              <Show when={checkout().step === "processing"}>
                <div style={{ "text-align": "center", padding: "40px 0" }}>
                  <div style={{ "margin-bottom": "16px" }}>
                    <div
                      style={{
                        width: "48px",
                        height: "48px",
                        border: "4px solid #E5E7EB",
                        "border-top-color": "#FF5E13",
                        "border-radius": "50%",
                        animation: "spin 1s linear infinite",
                        margin: "0 auto",
                      }}
                    />
                  </div>
                  <p style={{ margin: "0", "font-size": "16px", color: "#111827" }}>
                    Processing Payment...
                  </p>
                  <p style={{ margin: "8px 0 0", "font-size": "13px", color: "#6B7280" }}>
                    Please wait while we process your payment.
                  </p>
                </div>
              </Show>

              {/* Payment Form */}
              <Show when={checkout().step === "form"}>
                <div style={{ display: "flex", "flex-direction": "column", gap: "14px" }}>
                  <Show when={checkout().error}>
                    <div
                      style={{
                        background: "#FEF2F2",
                        border: "1px solid #FECACA",
                        "border-radius": "8px",
                        padding: "12px",
                        color: "#B91C1C",
                        "font-size": "13px",
                      }}
                    >
                      {checkout().error}
                    </div>
                  </Show>

                  {/* PayU Notice */}
                  <div
                    style={{
                      background: "#FFF7ED",
                      border: "1px solid #FDBA74",
                      "border-radius": "8px",
                      padding: "12px",
                      "font-size": "13px",
                      color: "#9A3412",
                    }}
                  >
                    PayU Secure Checkout will open in a secure page. Cancelled or failed
                    payments will not be credited.
                  </div>

                  {/* Pay Button */}
                  <button
                    onClick={processPayment}
                    style={{
                      ...BTN_PRIMARY,
                      width: "100%",
                      padding: "14px",
                      "font-size": "15px",
                      "font-weight": "700",
                    }}
                  >
                    Pay {formatCurrency(checkout().package ? checkout().package!.price : checkout().aiCreditPackage!.price_inr)}
                  </button>

                  <p
                    style={{
                      margin: "0",
                      "font-size": "11px",
                      color: "#9CA3AF",
                      "text-align": "center",
                    }}
                  >
                    Secure payment powered by PayU
                  </p>
                </div>
              </Show>
            </div>
          </div>
          <style>{`
            @keyframes spin {
              to { transform: rotate(360deg); }
            }
          `}</style>
        </Portal>
      </Show>
    );

  return (
    <div style={{ display: "grid", gap: "14px", "max-width": "980px" }}>
      <CheckoutModal />

      <div
        style={{
          background: NAVY,
          "border-radius": "12px",
          padding: "16px 20px",
          display: "flex",
          "align-items": "center",
          "justify-content": "space-between",
          "flex-wrap": "wrap",
          gap: "12px",
        }}
      >
        <div>
          <p style={{ margin: "0", "font-size": "18px", "font-weight": "800", color: "#fff" }}>
            Credits & Billing
          </p>
          <p style={{ margin: "4px 0 0", "font-size": "13px", color: "rgba(255,255,255,0.65)" }}>
            Manage your Tracecoin balance, purchase packages, and view transaction history.
          </p>
        </div>
        <Show when={isProfessional()}>
          <button
            type="button"
            onClick={() => setActiveTab("buy_credits")}
            style={BTN_ORANGE}
          >
            Buy Credits
          </button>
        </Show>
      </div>

      <Show when={err()}>
        <div
          style={{
            ...CARD,
            border: "1px solid #FECACA",
            background: "#FEF2F2",
            padding: "12px 14px",
            color: "#B91C1C",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {err()}
        </div>
      </Show>

      <Show when={msg()}>
        <div
          style={{
            ...CARD,
            border: "1px solid #BBF7D0",
            background: "#ECFDF5",
            padding: "12px 14px",
            color: "#065F46",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {msg()}
        </div>
      </Show>

      <Show when={lowBalanceWarning() && isProfessional() && Number(wallet()?.available ?? 0) >= 0}>
        <div
          style={{
            ...CARD,
            border: "1px solid #FCD34D",
            background: "#FFFBEB",
            padding: "12px 14px",
            color: "#92400E",
            "font-size": "13px",
            display: "flex",
            "align-items": "center",
            "justify-content": "space-between",
            gap: "12px",
          }}
        >
          <span>
            <strong>Heads up:</strong> your available tracecoins are below {LOW_BALANCE_THRESHOLD}.
            Top up to keep sending lead requests.
          </span>
          <button
            type="button"
            onClick={() => setActiveTab("buy_credits")}
            style={{
              padding: "6px 14px",
              background: "#F59E0B",
              color: "#fff",
              border: "none",
              "border-radius": "6px",
              "font-size": "12px",
              "font-weight": "600",
              cursor: "pointer",
            }}
          >
            Top up
          </button>
        </div>
      </Show>

      {/* Tabs */}
      <div
        style={{
          display: "flex",
          gap: "0",
          "border-bottom": "1px solid #E5E7EB",
        }}
      >
        <button
          type="button"
          onClick={() => setActiveTab("overview")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "overview" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "overview" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "overview" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          Overview
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("buy_credits")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "buy_credits" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "buy_credits" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "buy_credits" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          Buy Credits
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("buy_ai_credits")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "buy_ai_credits" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "buy_ai_credits" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "buy_ai_credits" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          AI Credits
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("ai_usage")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "ai_usage" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "ai_usage" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "ai_usage" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          AI Usage
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("holds")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "holds" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "holds" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "holds" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          Holds {holds().length > 0 ? `(${holds().length})` : ""}
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("transactions")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "transactions" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "transactions" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "transactions" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          Transactions
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("usage_history")}
          style={{
            padding: "10px 16px",
            "border-bottom": activeTab() === "usage_history" ? "2px solid #FF5E13" : "2px solid transparent",
            background: "transparent",
            color: activeTab() === "usage_history" ? "#FF5E13" : "#6B7280",
            "font-size": "14px",
            "font-weight": activeTab() === "usage_history" ? "700" : "500",
            cursor: "pointer",
            "margin-bottom": "-1px",
          }}
        >
          Usage History
        </button>
        <button
          type="button"
          onClick={loadAllData}
          style={{ ...BTN_GHOST, "margin-left": "auto", "margin-bottom": "-1px", "align-self": "flex-end" }}
        >
          Refresh
        </button>
      </div>

      <Show when={loading()}>
        <div style={{ ...CARD, "text-align": "center", color: "#9CA3AF" }}>Loading credits...</div>
      </Show>

      {/* Overview Tab */}
      <Show when={!loading() && activeTab() === "overview"}>
        <Show when={!isProfessional()}>
          <div style={CARD}>
            <p style={{ margin: "0", "font-size": "15px", "font-weight": "700", color: "#111827" }}>
              Billing Overview
            </p>
            <p style={{ margin: "8px 0 0", "font-size": "13px", color: "#6B7280" }}>
              Your role does not use professional wallet endpoints. Billing and payments are managed
              through role-specific transactions.
            </p>
          </div>
        </Show>

        <Show when={isProfessional()}>
          <div style={CARD}>
            <p
              style={{
                margin: "0",
                "font-size": "12px",
                "letter-spacing": "0.06em",
                "text-transform": "uppercase",
                color: "#6B7280",
              }}
            >
              Current Balance
            </p>
            <p
              style={{
                margin: "6px 0 0",
                "font-size": "36px",
                "font-weight": "800",
                color: NAVY,
              }}
            >
              {wallet()?.balance ?? 0}{" "}
              <span style={{ "font-size": "16px", color: "#6B7280", "font-weight": "600" }}>
                Tracecoins
              </span>
            </p>
          </div>

          <div style={CARD}>
            <p
              style={{
                margin: "0",
                "font-size": "12px",
                "letter-spacing": "0.06em",
                "text-transform": "uppercase",
                color: "#6B7280",
              }}
            >
              AI Plan
            </p>
            <p
              style={{
                margin: "6px 0 0",
                "font-size": "24px",
                "font-weight": "800",
                color: NAVY,
              }}
            >
              {aiSummary()?.plan_name ?? "Free"}
            </p>
            <p style={{ margin: "6px 0 0", "font-size": "13px", color: "#6B7280" }}>
              {aiSummary()?.remaining_credits ?? 0} credits remaining · {aiSummary()?.remaining_daily_actions ?? 0}/{aiSummary()?.daily_action_limit ?? 0} daily actions
            </p>
          </div>

          <div style={CARD}>
            <p
              style={{
                margin: "0 0 10px",
                "font-size": "16px",
                "font-weight": "700",
                color: "#111827",
              }}
            >
              Recent Ledger
            </p>
            <Show when={ledger().length === 0}>
              <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
                No ledger entries yet.
              </p>
            </Show>
            <Show when={ledger().length > 0}>
              <div style={{ display: "grid", gap: "8px" }}>
                <For each={ledger().slice(0, 5)}>
                  {(item: any) => (
                    <div
                      style={{
                        border: "1px solid #E5E7EB",
                        "border-radius": "10px",
                        padding: "10px",
                        background: "#FCFCFD",
                        display: "flex",
                        "justify-content": "space-between",
                        gap: "10px",
                        "flex-wrap": "wrap",
                      }}
                    >
                      <div>
                        <p
                          style={{
                            margin: "0",
                            "font-size": "13px",
                            "font-weight": "700",
                            color: "#111827",
                          }}
                        >
                          {item.reason || item.type || "Transaction"}
                        </p>
                        <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                          {item.created_at ? formatDate(item.created_at) : "—"}
                        </p>
                      </div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "13px",
                          "font-weight": "800",
                          color: Number(item.amount || 0) >= 0 ? "#15803D" : "#B91C1C",
                        }}
                      >
                        {Number(item.amount || 0) >= 0 ? "+" : ""}
                        {item.amount || 0}
                      </p>
                    </div>
                  )}
                </For>
              </div>
              <Show when={ledger().length > 5}>
                <button
                  type="button"
                  onClick={() => setActiveTab("transactions")}
                  style={{ ...BTN_GHOST, "margin-top": "10px", width: "100%" }}
                >
                  View All Transactions
                </button>
              </Show>
            </Show>
          </div>
        </Show>
      </Show>

      {/* Buy Credits Tab */}
      <Show when={!loading() && activeTab() === "buy_credits"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 10px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            Purchase Tracecoins
          </p>
          <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
            Select a package to purchase Tracecoins. These can be used to unlock leads and premium
            features.
          </p>

          <Show when={packages().length === 0}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              No packages available for your role.
            </p>
          </Show>

          <Show when={packages().length > 0}>
            {(() => {
              const pkgs = packages();
              const bestValue = pkgs.reduce((best, p) => {
                const ratio = p.tracecoins_amount / p.price;
                return ratio > best.ratio ? { pkg: p, ratio } : best;
              }, { pkg: pkgs[0], ratio: 0 });

              return (
                <div
                  style={{
                    display: "grid",
                    "grid-template-columns": "repeat(auto-fill, minmax(260px, 1fr))",
                    gap: "16px",
                  }}
                >
                  <For each={pkgs}>
                    {(pkg) => {
                      const theme = pkgCardTheme();
                      const isBestValue = bestValue.pkg.id === pkg.id;
                      const coinsPerRupee = (pkg.tracecoins_amount / pkg.price).toFixed(1);

                      return (
                        <div
                          style={{
                            border: isBestValue ? `2px solid ${ORANGE}` : `1px solid ${theme.BORDER_DEFAULT}`,
                            "border-radius": "16px",
                            padding: "0",
                            background: theme.WHITE,
                            display: "flex",
                            "flex-direction": "column",
                            overflow: "hidden",
                            "box-shadow": isBestValue
                              ? theme.SHADOW_ACCENT
                              : theme.SHADOW_DEFAULT,
                            transition: "transform 0.2s, box-shadow 0.2s",
                          }}
                        >
                          <Show when={isBestValue}>
                            <div
                              style={{
                                background: theme.BEST_VALUE_BG,
                                padding: "6px 12px",
                                "text-align": "center",
                              }}
                            >
                              <span
                                style={{
                                  color: theme.WHITE,
                                  "font-size": "11px",
                                  "font-weight": "700",
                                  "text-transform": "uppercase",
                                  "letter-spacing": "0.5px",
                                }}
                              >
                                Best Value
                              </span>
                            </div>
                          </Show>

                          <div style={{ padding: "20px", display: "flex", "flex-direction": "column", gap: "12px", flex: "1" }}>
                            <div>
                              <p
                                style={{
                                  margin: "0 0 4px",
                                  "font-size": "14px",
                                  "font-weight": "600",
                                  color: theme.TEXT_SECONDARY,
                                }}
                              >
                                {pkg.package_type}
                              </p>
                              <p
                                style={{
                                  margin: "0",
                                  "font-size": "18px",
                                  "font-weight": "800",
                                  color: theme.TEXT_PRIMARY,
                                }}
                              >
                                {pkg.name}
                              </p>
                            </div>

                            <div
                              style={{
                                display: "flex",
                                "align-items": "baseline",
                                gap: "4px",
                              }}
                            >
                              <span
                                style={{
                                  "font-size": "32px",
                                  "font-weight": "800",
                                  color: theme.TEXT_ACCENT,
                                }}
                              >
                                {formatCurrency(pkg.price)}
                              </span>
                              <span
                                style={{
                                  "font-size": "13px",
                                  color: theme.TEXT_MUTED,
                                }}
                              >
                                INR
                              </span>
                            </div>

                            <div
                              style={{
                                display: "flex",
                                "align-items": "center",
                                gap: "8px",
                                padding: "12px",
                                background: theme.COIN_BG,
                                "border-radius": "10px",
                              }}
                            >
                              <div
                                style={{
                                  width: "36px",
                                  height: "36px",
                                  "border-radius": "50%",
                                  background: theme.COIN_AVATAR_BG,
                                  display: "flex",
                                  "align-items": "center",
                                  "justify-content": "center",
                                }}
                              >
                                <span style={{ "font-size": "18px" }}>🪙</span>
                              </div>
                              <div>
                                <p
                                  style={{
                                    margin: "0",
                                    "font-size": "16px",
                                    "font-weight": "700",
                                    color: theme.TEXT_PRIMARY,
                                  }}
                                >
                                  {(pkg.tracecoins_amount ?? 0).toLocaleString()}
                                </p>
                                <p
                                  style={{
                                    margin: "0",
                                    "font-size": "11px",
                                    color: theme.TEXT_SECONDARY,
                                  }}
                                >
                                  Tracecoins
                                </p>
                              </div>
                            </div>

                            <div
                              style={{
                                "font-size": "12px",
                                color: theme.TEXT_SUCCESS,
                                "font-weight": "600",
                              }}
                            >
                              {coinsPerRupee} coins per ₹1
                            </div>

                            <Show when={pkg.description}>
                              <p
                                style={{
                                  margin: "0",
                                  "font-size": "13px",
                                  color: theme.TEXT_SECONDARY,
                                  "line-height": "1.5",
                                  flex: "1",
                                }}
                              >
                                {pkg.description}
                              </p>
                            </Show>

                            <button
                              type="button"
                              onClick={() => openCheckout(pkg)}
                              style={{
                                ...BTN_PRIMARY,
                                width: "100%",
                                "margin-top": "auto",
                                padding: "12px 16px",
                                "font-size": "14px",
                                "border-radius": "10px",
                              }}
                            >
                              Buy Now
                            </button>
                          </div>
                        </div>
                      );
                    }}
                  </For>
                </div>
              );
            })()}
          </Show>
        </div>
      </Show>

      {/* Buy AI Credits Tab */}
      <Show when={!loading() && activeTab() === "buy_ai_credits"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 10px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            Purchase AI Credits
          </p>
          <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
            Buy additional AI credits to power Ask Ash, cover letters, auto-apply, and more.
          </p>

          <Show when={aiPackages().length === 0}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              No AI credit packages available.
            </p>
          </Show>

          <Show when={aiPackages().length > 0}>
            <div
              style={{
                display: "grid",
                "grid-template-columns": "repeat(auto-fill, minmax(260px, 1fr))",
                gap: "16px",
              }}
            >
              <For each={aiPackages()}>
                {(pkg) => (
                  <div
                    style={{
                      border: "1px solid #E5E7EB",
                      "border-radius": "16px",
                      padding: "20px",
                      background: "#fff",
                      display: "flex",
                      "flex-direction": "column",
                      gap: "12px",
                    }}
                  >
                    <p
                      style={{
                        margin: "0",
                        "font-size": "18px",
                        "font-weight": "800",
                        color: "#111827",
                      }}
                    >
                      {pkg.name}
                    </p>
                    <p
                      style={{
                        margin: "0",
                        "font-size": "28px",
                        "font-weight": "800",
                        color: "#FF5E13",
                      }}
                    >
                      {formatCurrency(pkg.price_inr)}
                    </p>
                    <p style={{ margin: "0", "font-size": "14px", color: "#15803D", "font-weight": "700" }}>
                      +{pkg.credits} AI Credits
                    </p>
                    <Show when={pkg.description}>
                      <p style={{ margin: "0", "font-size": "13px", color: "#6B7280", flex: "1" }}>
                        {pkg.description}
                      </p>
                    </Show>
                    <button
                      type="button"
                      onClick={() => openAiCreditCheckout(pkg)}
                      style={{
                        ...BTN_PRIMARY,
                        width: "100%",
                        "margin-top": "auto",
                        padding: "12px 16px",
                        "font-size": "14px",
                        "border-radius": "10px",
                      }}
                    >
                      Buy Now
                    </button>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>

      {/* AI Usage Tab */}
      <Show when={!loading() && activeTab() === "ai_usage"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 10px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            AI Usage History
          </p>
          <Show when={aiSummary()}>
            {(s) => (
              <div
                style={{
                  display: "grid",
                  "grid-template-columns": "repeat(auto-fit, minmax(140px, 1fr))",
                  gap: "12px",
                  margin: "0 0 16px",
                }}
              >
                <div style={{ background: "#F9FAFB", "border-radius": "10px", padding: "12px" }}>
                  <p style={{ margin: "0", "font-size": "12px", color: "#6B7280" }}>Plan</p>
                  <p style={{ margin: "4px 0 0", "font-size": "16px", "font-weight": "700", color: "#111827" }}>
                    {s().plan_name}
                  </p>
                </div>
                <div style={{ background: "#F9FAFB", "border-radius": "10px", padding: "12px" }}>
                  <p style={{ margin: "0", "font-size": "12px", color: "#6B7280" }}>Credits Remaining</p>
                  <p style={{ margin: "4px 0 0", "font-size": "16px", "font-weight": "700", color: "#111827" }}>
                    {s().remaining_credits}
                  </p>
                </div>
                <div style={{ background: "#F9FAFB", "border-radius": "10px", padding: "12px" }}>
                  <p style={{ margin: "0", "font-size": "12px", color: "#6B7280" }}>Daily Actions</p>
                  <p style={{ margin: "4px 0 0", "font-size": "16px", "font-weight": "700", color: "#111827" }}>
                    {s().remaining_daily_actions}/{s().daily_action_limit}
                  </p>
                </div>
                <div style={{ background: "#F9FAFB", "border-radius": "10px", padding: "12px" }}>
                  <p style={{ margin: "0", "font-size": "12px", color: "#6B7280" }}>Monthly Used</p>
                  <p style={{ margin: "4px 0 0", "font-size": "16px", "font-weight": "700", color: "#111827" }}>
                    {s().monthly_credits_used}/{s().monthly_credits_total}
                  </p>
                </div>
              </div>
            )}
          </Show>

          <Show when={aiUsage().length === 0}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              No AI usage recorded yet.
            </p>
          </Show>

          <Show when={aiUsage().length > 0}>
            <div style={{ display: "grid", gap: "8px" }}>
              <For each={aiUsage()}>
                {(item) => (
                  <div
                    style={{
                      border: "1px solid #E5E7EB",
                      "border-radius": "10px",
                      padding: "12px",
                      background: "#FCFCFD",
                      display: "flex",
                      "justify-content": "space-between",
                      "align-items": "center",
                      gap: "10px",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "13px",
                          "font-weight": "700",
                          color: "#111827",
                        }}
                      >
                        {item.feature_code}
                      </p>
                      <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                        {item.model_alias} · {formatDate(item.created_at)}
                      </p>
                    </div>
                    <p
                      style={{
                        margin: "0",
                        "font-size": "14px",
                        "font-weight": "800",
                        color: item.status === "success" ? "#B91C1C" : "#6B7280",
                      }}
                    >
                      -{item.credits_charged} credits
                    </p>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>

      {/* Holds Tab */}
      <Show when={!loading() && activeTab() === "holds"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 6px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            Active Holds
          </p>
          <p
            style={{
              margin: "0 0 16px",
              "font-size": "13px",
              color: "#6B7280",
            }}
          >
            Holds earmark tracecoins for actions in flight (e.g. a lead request waiting on the
            customer). Releasing a hold returns the tracecoins to your available balance.
          </p>
          <Show
            when={holds().length > 0}
            fallback={
              <div
                style={{
                  background: "#F9FAFB",
                  "border-radius": "10px",
                  padding: "20px",
                  "text-align": "center",
                  color: "#6B7280",
                  "font-size": "13px",
                }}
              >
                No active holds. Submit a lead request or purchase to create a hold.
              </div>
            }
          >
            <div
              style={{
                display: "grid",
                "grid-template-columns": "1fr",
                gap: "10px",
              }}
            >
              <For each={holds()}>
                {(hold) => (
                  <div
                    style={{
                      display: "flex",
                      "align-items": "center",
                      gap: "12px",
                      padding: "14px",
                      "border-radius": "10px",
                      border: "1px solid #FED7AA",
                      background: "#FFFBEB",
                    }}
                  >
                    <div style={{ flex: 1 }}>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "14px",
                          "font-weight": "700",
                          color: "#9A3412",
                        }}
                      >
                        {hold.amount} TraceCoins held
                      </p>
                      <p
                        style={{
                          margin: "4px 0 0",
                          "font-size": "12px",
                          color: "#7C2D12",
                        }}
                      >
                        Reason: {hold.reason}
                        <Show when={hold.reference_id}>
                          {" "}· ref {hold.reference_id?.substring(0, 8)}…
                        </Show>
                        {hold.expires_at && (
                          <>
                            {" "}· expires {new Date(hold.expires_at).toLocaleString("en-IN")}
                          </>
                        )}
                      </p>
                      <p
                        style={{
                          margin: "2px 0 0",
                          "font-size": "11px",
                          color: "#9A3412",
                        }}
                      >
                        Created {new Date(hold.created_at).toLocaleString("en-IN")}
                      </p>
                    </div>
                    <button
                      type="button"
                      onClick={() => releaseHold(hold.id)}
                      disabled={releaseBusyId() === hold.id}
                      style={{
                        padding: "8px 14px",
                        background: "#fff",
                        "border-radius": "8px",
                        border: "1px solid #FCA5A5",
                        color: "#B91C1C",
                        "font-size": "12px",
                        "font-weight": "600",
                        cursor: "pointer",
                      }}
                    >
                      {releaseBusyId() === hold.id ? "Releasing..." : "Release"}
                    </button>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>

      {/* Transactions Tab */}
      <Show when={!loading() && activeTab() === "transactions"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 10px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            Transaction History
          </p>

          <Show when={loadingPayments()}>
            <p style={{ margin: "0", "font-size": "13px", color: "#9CA3AF" }}>
              Loading transactions...
            </p>
          </Show>

          <Show when={!loadingPayments() && payments().length === 0 && ledger().length === 0}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              No transactions found.
            </p>
          </Show>

          <Show when={!loadingPayments() && (payments().length > 0 || ledger().length > 0)}>
            <div style={{ display: "grid", gap: "8px" }}>
              <For each={ledger()}>
                {(item: any) => (
                  <div
                    style={{
                      border: "1px solid #E5E7EB",
                      "border-radius": "10px",
                      padding: "12px",
                      background: "#FCFCFD",
                      display: "flex",
                      "justify-content": "space-between",
                      "align-items": "center",
                      gap: "10px",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "13px",
                          "font-weight": "700",
                          color: "#111827",
                        }}
                      >
                        {item.reason || "Transaction"}
                      </p>
                      <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                        {formatDate(item.created_at)}
                      </p>
                    </div>
                    <div style={{ "text-align": "right" }}>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "14px",
                          "font-weight": "800",
                          color: Number(item.amount || 0) >= 0 ? "#15803D" : "#B91C1C",
                        }}
                      >
                        {Number(item.amount || 0) >= 0 ? "+" : ""}
                        {item.amount || 0} TC
                      </p>
                      <p style={{ margin: "2px 0 0", "font-size": "11px", color: "#9CA3AF" }}>
                        Ledger
                      </p>
                    </div>
                  </div>
                )}
              </For>

              <For each={payments()}>
                {(payment) => (
                  <div
                    style={{
                      border: "1px solid #E5E7EB",
                      "border-radius": "10px",
                      padding: "12px",
                      background: "#FCFCFD",
                      display: "flex",
                      "justify-content": "space-between",
                      "align-items": "center",
                      gap: "10px",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "13px",
                          "font-weight": "700",
                          color: "#111827",
                        }}
                      >
                        {payment.package_name || "Credit Purchase"}
                      </p>
                      <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                        {formatDate(payment.created_at)}
                      </p>
                    </div>
                    <div style={{ "text-align": "right" }}>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "14px",
                          "font-weight": "800",
                          color: "#111827",
                        }}
                      >
                        {formatCurrency(payment.amount_inr)}
                      </p>
                      <span
                        style={{
                          display: "inline-block",
                          padding: "2px 8px",
                          "border-radius": "6px",
                          "font-size": "11px",
                          "font-weight": "700",
                          background:
                            payment.status === "SUCCESS"
                              ? "#ECFDF5"
                              : payment.status === "FAILED"
                                ? "#FEF2F2"
                                : "#FFFBEB",
                          color:
                            payment.status === "SUCCESS"
                              ? "#15803D"
                              : payment.status === "FAILED"
                                ? "#B91C1C"
                                : "#D97706",
                        }}
                      >
                        {payment.status === "SUCCESS"
                          ? "✓ Completed"
                          : payment.status === "FAILED"
                            ? "✕ Failed"
                            : "◌ Pending"}
                      </span>
                      <Show when={payment.tracecoins_credited > 0}>
                        <p style={{ margin: "2px 0 0", "font-size": "11px", color: "#6B7280" }}>
                          +{payment.tracecoins_credited} TC
                        </p>
                      </Show>
                    </div>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>

      {/* Usage History Tab */}
      <Show when={!loading() && activeTab() === "usage_history"}>
        <div style={CARD}>
          <p
            style={{
              margin: "0 0 10px",
              "font-size": "16px",
              "font-weight": "700",
              color: "#111827",
            }}
          >
            Tracecoin Usage History
          </p>
          <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
            A record of all Tracecoins spent on leads, responses, and platform features.
          </p>

          <Show when={ledger().length === 0}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              No usage history yet.
            </p>
          </Show>

          <Show when={ledger().length > 0}>
            <div style={{ display: "grid", gap: "8px" }}>
              <For each={ledger().filter((item: any) => Number(item.amount) < 0)}>
                {(item: any) => (
                  <div
                    style={{
                      border: "1px solid #E5E7EB",
                      "border-radius": "10px",
                      padding: "12px",
                      background: "#FCFCFD",
                      display: "flex",
                      "justify-content": "space-between",
                      "align-items": "center",
                      gap: "10px",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "13px",
                          "font-weight": "700",
                          color: "#111827",
                        }}
                      >
                        {item.reason || item.type || "Tracecoins Used"}
                      </p>
                      <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                        {item.created_at ? formatDate(item.created_at) : "—"}
                      </p>
                    </div>
                    <p
                      style={{
                        margin: "0",
                        "font-size": "14px",
                        "font-weight": "800",
                        color: "#B91C1C",
                      }}
                    >
                      {item.amount} TC
                    </p>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>
    </div>
  );
}
