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

const API = "/api/gateway";

type Props = { roleKey: RoleKey };

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) {
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: { "Content-Type": "application/json", ...(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" | "transactions">("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 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 pkgs = Array.isArray(data?.data)
          ? data.data
          : Array.isArray(data?.packages)
            ? data.packages
            : [];
        setPackages(pkgs);
      }
    } 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) => {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 0,
    }).format(amount);
  };

  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={CARD}>
        <p style={{ margin: "0", "font-size": "22px", "font-weight": "800", color: "#0D0D2A" }}>
          Credits & Billing
        </p>
        <p style={{ margin: "4px 0 0", "font-size": "13px", color: "#6B7280" }}>
          Manage your Tracecoin balance, purchase packages, and view transaction history.
        </p>
      </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: "8px",
          borderBottom: "1px solid #E5E7EB",
          paddingBottom: "10px",
        }}
      >
        <button
          type="button"
          onClick={() => setActiveTab("overview")}
          style={{
            padding: "8px 16px",
            borderRadius: "8px",
            border: "none",
            background: activeTab() === "overview" ? "#FF5E13" : "transparent",
            color: activeTab() === "overview" ? "#fff" : "#6B7280",
            fontSize: "13px",
            fontWeight: "600",
            cursor: "pointer",
          }}
        >
          Overview
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("buy")}
          style={{
            padding: "8px 16px",
            borderRadius: "8px",
            border: "none",
            background: activeTab() === "buy" ? "#FF5E13" : "transparent",
            color: activeTab() === "buy" ? "#fff" : "#6B7280",
            fontSize: "13px",
            fontWeight: "600",
            cursor: "pointer",
          }}
        >
          Buy Credits
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("transactions")}
          style={{
            padding: "8px 16px",
            borderRadius: "8px",
            border: "none",
            background: activeTab() === "transactions" ? "#FF5E13" : "transparent",
            color: activeTab() === "transactions" ? "#fff" : "#6B7280",
            fontSize: "13px",
            fontWeight: "600",
            cursor: "pointer",
          }}
        >
          Transactions
        </button>
        <button type="button" onClick={loadAllData} style={{ ...BTN_GHOST, marginLeft: "auto" }}>
          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,
              display: "grid",
              "grid-template-columns": "1fr auto",
              gap: "10px",
              "align-items": "center",
            }}
          >
            <div>
              <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: "#111827",
                }}
              >
                {wallet()?.balance ?? 0}{" "}
                <span style={{ "font-size": "16px", color: "#6B7280", "font-weight": "600" }}>
                  Tracecoins
                </span>
              </p>
            </div>
            <button type="button" onClick={() => setActiveTab("buy")} style={BTN_PRIMARY}>
              Buy Credits
            </button>
          </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"}>
        <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}>
            <div
              style={{
                display: "grid",
                "grid-template-columns": "repeat(auto-fill, minmax(240px, 1fr))",
                gap: "14px",
              }}
            >
              <For each={packages()}>
                {(pkg) => (
                  <div
                    style={{
                      border: "2px solid #E5E7EB",
                      borderRadius: "12px",
                      padding: "16px",
                      background: "#fff",
                      display: "flex",
                      "flex-direction": "column",
                      gap: "8px",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "16px",
                          "font-weight": "800",
                          color: "#111827",
                        }}
                      >
                        {pkg.name}
                      </p>
                      <p
                        style={{
                          margin: "4px 0 0",
                          "font-size": "24px",
                          "font-weight": "800",
                          color: "#FF5E13",
                        }}
                      >
                        {formatCurrency(pkg.price)}
                      </p>
                    </div>
                    <div
                      style={{
                        display: "flex",
                        "align-items": "center",
                        gap: "6px",
                        margin: "8px 0",
                      }}
                    >
                      <span style={{ fontSize: "20px" }}>🪙</span>
                      <span style={{ fontSize: "15px", "font-weight": "700", color: "#111827" }}>
                        {pkg.tracecoins_amount} Tracecoins
                      </span>
                    </div>
                    <Show when={pkg.description}>
                      <p style={{ margin: "0", "font-size": "12px", color: "#6B7280", flex: "1" }}>
                        {pkg.description}
                      </p>
                    </Show>
                    <button
                      type="button"
                      onClick={() => openCheckout(pkg)}
                      style={{
                        ...BTN_PRIMARY,
                        width: "100%",
                        "margin-top": "8px",
                      }}
                    >
                      Buy Now
                    </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={{ 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>
                      <p
                        style={{
                          margin: "2px 0 0",
                          "font-size": "12px",
                          color: payment.status === "SUCCESS" ? "#15803D" : "#D97706",
                        }}
                      >
                        {payment.status === "SUCCESS" ? "✓ Completed" : payment.status}
                      </p>
                      <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>
    </div>
  );
}
