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";

const API = "/api/gateway";

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 CheckoutState = {
  package: Package | 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") || ""
      : "";
  const cleanPath = path.startsWith("/api/") ? path.slice(4) : path;
  return fetch(`${API}${cleanPath}`, {
    ...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 [loading, setLoading] = createSignal(true);
  const [loadingPayments, setLoadingPayments] = createSignal(false);
  const [err, setErr] = createSignal("");
  const [msg, setMsg] = createSignal("");
  const [activeTab, setActiveTab] = createSignal<"overview" | "buy_credits" | "transactions" | "usage_history">("overview");

  // Checkout modal state
  const [checkout, setCheckout] = createSignal<CheckoutState>({
    package: null,
    orderId: null,
    step: "form",
    error: "",
  });

  // Mock card form state
  const [cardNumber, setCardNumber] = createSignal("");
  const [cardExpiry, setCardExpiry] = createSignal("");
  const [cardCvv, setCardCvv] = createSignal("");
  const [cardName, setCardName] = createSignal("");

  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] = await Promise.all([
        apiFetch(`/api/${prefix()}/wallet/me`),
        apiFetch(`/api/${prefix()}/wallet/me/ledger?page=1&limit=20`),
      ]);
      const walletJson = await walletRes.json().catch(() => ({}));
      const ledgerJson = await ledgerRes.json().catch(() => ({}));
      if (walletRes.ok) setWallet(walletJson);
      if (ledgerRes.ok) setLedger(Array.isArray(ledgerJson?.data) ? ledgerJson.data : []);
    } catch {
      // non-blocking
    }
  };

  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/history?page=1&limit=50");
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setPayments(Array.isArray(data?.payments) ? data.payments : []);
      } else {
        setPayments([]);
      }
    } catch {
      setPayments([]);
    } finally {
      setLoadingPayments(false);
    }
  };

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

  onMount(loadAllData);

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

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

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

    // Validate card fields
    if (cardNumber().replace(/\s/g, "").length < 16) {
      setCheckout((c) => ({ ...c, error: "Please enter a valid card number" }));
      return;
    }
    if (!cardExpiry() || cardExpiry().length < 5) {
      setCheckout((c) => ({ ...c, error: "Please enter expiry date (MM/YY)" }));
      return;
    }
    if (cardCvv().length < 3) {
      setCheckout((c) => ({ ...c, error: "Please enter valid CVV" }));
      return;
    }

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

    try {
      // Step 1: Create order
      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 orderId = orderData.order_id;

      // Step 2: Simulate payment processing (mock)
      await new Promise((resolve) => setTimeout(resolve, 2000));

      // Step 3: Verify payment
      const verifyRes = await apiFetch("/api/payments/verify", {
        method: "POST",
        body: JSON.stringify({
          order_id: orderId,
          payment_id: "pay_mock_" + Date.now(),
          signature: "mock_signature",
        }),
      });
      const verifyData = await verifyRes.json().catch(() => ({}));

      if (verifyRes.ok && verifyData.verified) {
        setCheckout((c) => ({ ...c, step: "success", orderId }));
        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 formatCardNumber = (value: string) => {
    const digits = value.replace(/\D/g, "").slice(0, 16);
    return digits.replace(/(\d{4})(?=\d)/g, "$1 ");
  };

  const formatExpiry = (value: string) => {
    const digits = value.replace(/\D/g, "").slice(0, 4);
    if (digits.length >= 2) {
      return digits.slice(0, 2) + "/" + digits.slice(2);
    }
    return digits;
  };

  const CheckoutModal = () => {
    const state = checkout();
    const pkg = state.package;
    if (!pkg) return null;

    return (
      <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 && state.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" }}
              >
                {state.step === "success"
                  ? "✓ Payment Successful"
                  : state.step === "error"
                    ? "Payment Failed"
                    : "Checkout"}
              </h3>
              <Show when={state.step !== "processing"}>
                <button
                  onClick={closeCheckout}
                  style={{
                    background: "none",
                    border: "none",
                    cursor: "pointer",
                    "font-size": "24px",
                    color: "#9CA3AF",
                  }}
                >
                  ×
                </button>
              </Show>
            </div>

            {/* Package Summary */}
            <Show when={state.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",
                  }}
                >
                  {pkg.name}
                </p>
                <p
                  style={{
                    margin: "0",
                    "font-size": "24px",
                    "font-weight": "800",
                    color: "#FF5E13",
                  }}
                >
                  {formatCurrency(pkg.price)}
                </p>
                <p style={{ margin: "8px 0 0", "font-size": "14px", color: "#15803D" }}>
                  +{pkg.tracecoins_amount} Tracecoins
                </p>
              </div>
            </Show>

            {/* Success State */}
            <Show when={state.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" }}>
                  {pkg.tracecoins_amount} Tracecoins have been credited to your wallet.
                </p>
                <p style={{ margin: "0", "font-size": "12px", color: "#9CA3AF" }}>
                  Order ID: {state.orderId}
                </p>
              </div>
              <button
                onClick={closeCheckout}
                style={{ ...BTN_PRIMARY, width: "100%", "margin-top": "16px" }}
              >
                Done
              </button>
            </Show>

            {/* Error State */}
            <Show when={state.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" }}>
                  {state.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={state.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={state.step === "form"}>
              <div style={{ display: "flex", "flex-direction": "column", gap: "14px" }}>
                <Show when={state.error}>
                  <div
                    style={{
                      background: "#FEF2F2",
                      border: "1px solid #FECACA",
                      "border-radius": "8px",
                      padding: "12px",
                      color: "#B91C1C",
                      "font-size": "13px",
                    }}
                  >
                    {state.error}
                  </div>
                </Show>

                {/* Mock Notice */}
                <div
                  style={{
                    background: "#FEF3C7",
                    border: "1px solid #FCD34D",
                    "border-radius": "8px",
                    padding: "10px",
                    "font-size": "12px",
                    color: "#92400E",
                  }}
                >
                  <strong>Mock Payment:</strong> Use any values. This is a simulation.
                </div>

                {/* Card Number */}
                <div>
                  <label
                    style={{
                      display: "block",
                      "font-size": "12px",
                      "font-weight": "600",
                      color: "#374151",
                      "margin-bottom": "6px",
                    }}
                  >
                    Card Number
                  </label>
                  <input
                    type="text"
                    value={cardNumber()}
                    onInput={(e) => setCardNumber(formatCardNumber(e.currentTarget.value))}
                    placeholder="1234 5678 9012 3456"
                    maxLength="19"
                    style={{
                      width: "100%",
                      padding: "12px",
                      border: "1px solid #E5E7EB",
                      "border-radius": "8px",
                      "font-size": "14px",
                      "box-sizing": "border-box",
                    }}
                  />
                </div>

                {/* Expiry & CVV */}
                <div style={{ display: "grid", "grid-template-columns": "1fr 1fr", gap: "12px" }}>
                  <div>
                    <label
                      style={{
                        display: "block",
                        "font-size": "12px",
                        "font-weight": "600",
                        color: "#374151",
                        "margin-bottom": "6px",
                      }}
                    >
                      Expiry (MM/YY)
                    </label>
                    <input
                      type="text"
                      value={cardExpiry()}
                      onInput={(e) => setCardExpiry(formatExpiry(e.currentTarget.value))}
                      placeholder="MM/YY"
                      maxLength="5"
                      style={{
                        width: "100%",
                        padding: "12px",
                        border: "1px solid #E5E7EB",
                        "border-radius": "8px",
                        "font-size": "14px",
                        "box-sizing": "border-box",
                      }}
                    />
                  </div>
                  <div>
                    <label
                      style={{
                        display: "block",
                        "font-size": "12px",
                        "font-weight": "600",
                        color: "#374151",
                        "margin-bottom": "6px",
                      }}
                    >
                      CVV
                    </label>
                    <input
                      type="text"
                      value={cardCvv()}
                      onInput={(e) =>
                        setCardCvv(e.currentTarget.value.replace(/\D/g, "").slice(0, 4))
                      }
                      placeholder="123"
                      maxLength="4"
                      style={{
                        width: "100%",
                        padding: "12px",
                        border: "1px solid #E5E7EB",
                        "border-radius": "8px",
                        "font-size": "14px",
                        "box-sizing": "border-box",
                      }}
                    />
                  </div>
                </div>

                {/* Cardholder Name */}
                <div>
                  <label
                    style={{
                      display: "block",
                      "font-size": "12px",
                      "font-weight": "600",
                      color: "#374151",
                      "margin-bottom": "6px",
                    }}
                  >
                    Cardholder Name
                  </label>
                  <input
                    type="text"
                    value={cardName()}
                    onInput={(e) => setCardName(e.currentTarget.value)}
                    placeholder="John Doe"
                    style={{
                      width: "100%",
                      padding: "12px",
                      border: "1px solid #E5E7EB",
                      "border-radius": "8px",
                      "font-size": "14px",
                      "box-sizing": "border-box",
                    }}
                  />
                </div>

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

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

  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>

      {/* 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("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 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={{ fontSize: "18px" }}>🪙</span>
                              </div>
                              <div>
                                <p
                                  style={{
                                    margin: "0",
                                    "font-size": "16px",
                                    "font-weight": "700",
                                    color: theme.TEXT_PRIMARY,
                                  }}
                                >
                                  {pkg.tracecoins_amount.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>

      {/* 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={{ textAlign: "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={{ textAlign: "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>
  );
}
