import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, useActionData, useSubmit, Form } from "react-router";
import { useEffect } from "react";
import {
  Page,
  Layout,
  Card,
  Text,
  BlockStack,
  InlineGrid,
  InlineStack,
  Badge,
  Banner,
  Button,
  Box,
  List,
  Divider,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";
import { registerShop } from "../services/shop.server";
import { BillingService } from "../services/billing.server";
import { PLAN_CONFIGS, FEATURE_MATRIX_ROWS } from "../lib/billing-plans";
import { getActivePlans, getAllPlans } from "../services/plan-config.server";
import { FAIcon } from "../components/FAIcon";
import { resolveShopDomainFromRequest } from "../lib/security/tenant-context";

export const headers = () => {
  return {
    "X-Frame-Options": "ALLOWALL",
    "Content-Security-Policy": "frame-ancestors https://admin.shopify.com https://*.myshopify.com;",
  };
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const syncRequested = url.searchParams.get("sync") === "true";
  const chargeId = url.searchParams.get("charge_id");
  const returnPlan = url.searchParams.get("plan");

  let shopDomain = "";
  let accessToken: string | undefined;

  try {
    const authResult = await authenticate.admin(request);
    shopDomain = authResult?.session?.shop || "";
    accessToken = authResult?.session?.accessToken;
  } catch (authErr) {
    // Top-level browser return from Shopify charge approval
  }

  if (!shopDomain) {
    const rawShop = url.searchParams.get("shop");
    if (rawShop) {
      shopDomain = rawShop.includes(".") ? rawShop.toLowerCase().trim() : `${rawShop.toLowerCase().trim()}.myshopify.com`;
    }
  }

  if (!shopDomain) {
    shopDomain = resolveShopDomainFromRequest(request);
  }

  if (!shopDomain || shopDomain === "digi-horizon.myshopify.com") {
    try {
      const recentShop = await prisma.shop.findFirst({
        orderBy: { updatedAt: "desc" },
      });
      if (recentShop?.shopifyDomain) {
        shopDomain = recentShop.shopifyDomain;
      }
    } catch {}
  }

  // Ensure shop record exists in database
  let shopRecord: any = null;
  try {
    shopRecord = await registerShop({
      shopifyDomain: shopDomain,
      accessToken: accessToken || "shpss_sample_token",
      scopes: "read_products,read_content",
    });
  } catch (regErr) {
    console.warn("[Billing] Shop registration warning:", regErr);
  }

  // If returning from Shopify charge approval, activate the plan in database
  if (chargeId || (syncRequested && returnPlan)) {
    const targetPlan = (returnPlan || "STARTER").toUpperCase();
    if (targetPlan && targetPlan !== "FREE") {
      try {
        const { SubscriptionService } = await import("../services/subscription.server");
        const shop = shopRecord || (await prisma.shop.findUnique({ where: { shopifyDomain: shopDomain } }));
        if (shop) {
          await SubscriptionService.changePlan({
            shopId: shop.id,
            newPlan: targetPlan as any,
          });
        }
      } catch (e) {
        await prisma.shop.updateMany({
          where: { shopifyDomain: shopDomain },
          data: {
            activePlan: targetPlan as any,
            planHandle: targetPlan.toLowerCase(),
            subscriptionStatus: "ACTIVE",
          },
        }).catch(() => null);
      }
    }

    // Break back into Shopify Admin embedded frame if opened as top-level window
    const isTopLevelWindow = !url.searchParams.get("host");
    if (isTopLevelWindow && shopDomain) {
      const shopSubdomain = shopDomain.replace(/\.myshopify\.com$/i, "");
      const appHandle = process.env.SHOPIFY_APP_HANDLE || "commercebot-ai";
      const embeddedAppUrl = `https://admin.shopify.com/store/${shopSubdomain}/apps/${appHandle}/app/billing?sync=true&plan=${encodeURIComponent(targetPlan)}`;

      return new Response(
        `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Redirecting to Shopify Admin...</title>
  <script>
    try {
      if (window.top && window.top !== window) {
        window.top.location.href = ${JSON.stringify(embeddedAppUrl)};
      } else {
        window.location.href = ${JSON.stringify(embeddedAppUrl)};
      }
    } catch (e) {
      window.location.href = ${JSON.stringify(embeddedAppUrl)};
    }
  </script>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 80vh; margin: 0; background: #f8fafc;">
  <div style="text-align: center; max-width: 440px; padding: 32px; background: white; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.06); border: 1px solid #e2e8f0;">
    <div style="font-size: 32px; margin-bottom: 12px;">🎉</div>
    <h3 style="margin: 0 0 8px; color: #1e293b; font-size: 20px;">Subscription Activated!</h3>
    <p style="color: #64748b; font-size: 14px; margin-bottom: 20px; line-height: 1.5;">Redirecting back to your Shopify app dashboard...</p>
    <a href="${embeddedAppUrl}" target="_top" style="display: inline-block; padding: 12px 24px; background: #4f46e5; color: white; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px;">
      Click here to open app &rarr;
    </a>
  </div>
</body>
</html>`,
        {
          status: 200,
          headers: { "Content-Type": "text/html; charset=utf-8" },
        }
      );
    }
  }

  // Fetch verified active subscription state with safe fallback
  let planInfo: any;
  try {
    planInfo = syncRequested
      ? await BillingService.syncSubscription(shopDomain)
      : await BillingService.getActiveSubscription(shopDomain);
  } catch (planErr: any) {
    console.warn("[Billing] Subscription lookup fallback:", planErr?.message);
    const fallbackPlan = PLAN_CONFIGS.FREE;
    planInfo = {
      shopDomain,
      shopId: shopRecord?.id || "",
      shopifyShopId: null,
      shopifyAppId: null,
      plan: "FREE",
      planHandle: "free",
      displayName: fallbackPlan.displayName,
      price: fallbackPlan.price,
      currency: "USD",
      billingPeriod: "EVERY_30_DAYS",
      status: "ACTIVE",
      statusState: "FREE",
      isTrial: false,
      trialEndsAt: null,
      cancelAtEndOfCycle: false,
      currentBillingCycleStart: null,
      currentBillingCycleEnd: null,
      lastSubscriptionSync: null,
      pricingPlansUrl: BillingService.getPricingUrl(shopDomain),
      features: fallbackPlan.features,
    };
  }

  const pricingUrl = BillingService.getPricingUrl(shopDomain);

  let activePlans: any[] = [];
  try {
    activePlans = await getActivePlans();
  } catch {
    activePlans = [];
  }

  if (!activePlans || activePlans.length < 2) {
    activePlans = [
      {
        id: "plan_free",
        planKey: "FREE",
        displayName: "Free",
        price: 0.0,
        billingType: "RECURRING",
        billingInterval: "MONTHLY",
        aiUsageEnabled: false,
        aiMonthlyLimit: null,
        monthlyLimit: 0,
        description: "Shopify API catalog integration & product search",
        featureFlags: PLAN_CONFIGS.FREE.featureFlags,
        features: PLAN_CONFIGS.FREE.features,
        sortOrder: 1,
        isActive: true,
      },
      {
        id: "plan_starter",
        planKey: "STARTER",
        displayName: "Starter",
        price: 29.0,
        billingType: "RECURRING",
        billingInterval: "MONTHLY",
        aiUsageEnabled: false,
        aiMonthlyLimit: null,
        monthlyLimit: 0,
        description: "Full Commerce, Cart & Shopify Checkout",
        featureFlags: PLAN_CONFIGS.STARTER.featureFlags,
        features: PLAN_CONFIGS.STARTER.features,
        sortOrder: 2,
        isActive: true,
      },
      {
        id: "plan_pro",
        planKey: "PRO",
        displayName: "Pro",
        price: 79.0,
        billingType: "RECURRING",
        billingInterval: "MONTHLY",
        aiUsageEnabled: true,
        aiMonthlyLimit: null,
        monthlyLimit: 0,
        description: "AI Sales Assistant & BYOK (OpenAI / Gemini)",
        featureFlags: PLAN_CONFIGS.PRO.featureFlags,
        features: PLAN_CONFIGS.PRO.features,
        sortOrder: 3,
        isActive: true,
      },
    ];
  }

  const safeIso = (d: any): string | null => {
    if (!d) return null;
    try {
      const date = d instanceof Date ? d : new Date(d);
      return isNaN(date.getTime()) ? null : date.toISOString();
    } catch {
      return null;
    }
  };

  let hasValidToken = true;
  try {
    const { getShopWithDecryptedToken } = await import("../services/shop.server");
    const shopWithToken = await getShopWithDecryptedToken(shopDomain);
    const tok = shopWithToken?.decryptedAccessToken || "";
    const isUninstalled = Boolean(shopWithToken?.uninstalledAt);
    if (shopWithToken) {
      hasValidToken = Boolean(tok && tok !== "shpss_sample_token" && !isUninstalled);
    } else {
      hasValidToken = true;
    }
  } catch {
    hasValidToken = true;
  }

  const authUrl = `/auth?shop=${encodeURIComponent(shopDomain)}&returnTo=${encodeURIComponent("/app/billing")}`;

  return {
    shop: shopDomain,
    hasValidToken,
    authUrl,
    planInfo: {
      ...planInfo,
      pricingPlansUrl: pricingUrl,
      currentBillingCycleStart: safeIso(planInfo?.currentBillingCycleStart),
      currentBillingCycleEnd: safeIso(planInfo?.currentBillingCycleEnd),
      trialEndsAt: safeIso(planInfo?.trialEndsAt),
      lastSubscriptionSync: safeIso(planInfo?.lastSubscriptionSync),
    },
    pricingPlansUrl: pricingUrl,
    allConfiguredPlans: activePlans,
    activePlans,
  };
};

export const action = async ({ request }: ActionFunctionArgs) => {
  let sessionShop = "";
  let sessionAccessToken = "";

  const formData = await request.formData();
  const intent = formData.get("intent") as string;
  const requestedPlan = String(formData.get("plan") || "").toUpperCase();
  const shopFromForm = String(formData.get("shop") || "").toLowerCase().trim();

  try {
    const authResult = await authenticate.admin(request);
    sessionShop = authResult?.session?.shop || "";
    sessionAccessToken = authResult?.session?.accessToken || "";
  } catch (authErr) {
    const isMainDevStore = shopFromForm === "digi-horizon.myshopify.com" || shopFromForm === "digi-horizon";
    if (authErr instanceof Response && intent !== "test_switch" && !isMainDevStore) {
      throw authErr;
    }
  }

  if (shopFromForm) {
    sessionShop = shopFromForm.includes(".") ? shopFromForm : `${shopFromForm}.myshopify.com`;
  }

  if (!sessionShop) {
    sessionShop = resolveShopDomainFromRequest(request);
  }

  if (intent === "sync") {
    try {
      const planInfo = await BillingService.syncSubscription(sessionShop);
      return { success: true, message: `Subscription state synchronized with Shopify. Active plan: ${planInfo.displayName}.` };
    } catch (e: any) {
      return { success: false, message: `Subscription sync error: ${e?.message || "Unknown error"}` };
    }
  }

  if (intent === "test_switch" || intent === "subscribe" || intent === "upgrade" || intent === "downgrade") {
    let shopRecord = await prisma.shop.findUnique({
      where: { shopifyDomain: sessionShop },
    });

    if (!shopRecord) {
      try {
        shopRecord = await registerShop({
          shopifyDomain: sessionShop,
          accessToken: sessionAccessToken || "shpss_sample_token",
          scopes: "read_products,read_content",
        });
      } catch (err: any) {
        return { success: false, message: `Shop record error: ${err?.message}` };
      }
    }

    // 1. Instant 1-Click Plan Switch STRICTLY & EXCLUSIVELY for main digi-horizon development store
    const isDigiHorizonTestStore = sessionShop.toLowerCase() === "digi-horizon.myshopify.com" || sessionShop.toLowerCase() === "digi-horizon";

    if (isDigiHorizonTestStore) {
      try {
        const { SubscriptionService } = await import("../services/subscription.server");
        await SubscriptionService.changePlan({
          shopId: shopRecord.id,
          newPlan: (requestedPlan || "FREE") as any,
        });
        const planName = requestedPlan === "PRO" ? "Pro ($79/mo - Full AI & BYOK)" : requestedPlan === "STARTER" ? "Starter ($29/mo - Cart & Checkout)" : "Free ($0)";
        return {
          success: true,
          message: `[Test Mode] Store plan instantly switched to ${planName}! All plan features and API access are active with $0 charge.`,
        };
      } catch (e: any) {
        return { success: false, message: `Failed to update test plan: ${e?.message || "Unknown error"}` };
      }
    }

    // Reject test_switch intent for any other store
    if (intent === "test_switch") {
      return { success: false, message: "1-Click test switching is not permitted for this store." };
    }

    // 2. Revert / Downgrade back to FREE plan
    if (requestedPlan === "FREE") {
      try {
        await BillingService.cancelSubscription(sessionShop);
        const { SubscriptionService } = await import("../services/subscription.server");
        await SubscriptionService.changePlan({
          shopId: shopRecord.id,
          newPlan: "FREE",
        });
      } catch (e: any) {
        await prisma.shop.updateMany({
          where: { shopifyDomain: sessionShop },
          data: { activePlan: "FREE", planHandle: "free", subscriptionStatus: "ACTIVE" },
        }).catch(() => null);
      }
      return {
        success: true,
        message: "Successfully reverted back to Free plan! All core catalog search capabilities remain active.",
      };
    }

    // 3. Initiate official Shopify Recurring Application Charge via GraphQL (Shopify Manual Pricing)
    try {
      const appUrl = process.env.SHOPIFY_APP_URL || new URL(request.url).origin;
      const returnUrl = `${appUrl}/app/billing?sync=true&plan=${requestedPlan || "STARTER"}&shop=${encodeURIComponent(sessionShop)}`;
      const isTestStore = sessionShop.toLowerCase().includes("digi-horizon") ||
                          sessionShop.toLowerCase().includes("dev") ||
                          sessionShop.toLowerCase().includes("test") ||
                          process.env.SHOPIFY_BILLING_TEST === "true" ||
                          process.env.NODE_ENV !== "production";

      const subResult = await BillingService.createSubscription({
        shopDomainOrId: sessionShop,
        plan: requestedPlan || "STARTER",
        returnUrl,
        explicitAccessToken: sessionAccessToken,
        isTest: isTestStore,
      });

      if (subResult?.confirmationUrl) {
        return {
          success: true,
          confirmationUrl: subResult.confirmationUrl,
          isRedirect: true,
          message: `Shopify subscription created! Redirecting to Shopify for approval...`,
        };
      }
    } catch (err: any) {
      console.warn("[Billing createSubscription error]:", err?.message);
      const errMsg = err?.message || "";
      const isMissingToken = errMsg.includes("No active access token found");
      const isInvalidToken = errMsg.includes("401") ||
                             errMsg.includes("Invalid API key or access token") ||
                             errMsg.includes("unrecognized login") ||
                             errMsg.includes("wrong password");
      const isDeprecationError = errMsg.includes("Non-expiring access tokens are no longer accepted") || 
                                 errMsg.includes("non-expiring access tokens are deprecated") || 
                                 errMsg.includes("re-authentication") ||
                                 errMsg.includes("re-authorization");
      const authUrl = `/auth?shop=${encodeURIComponent(sessionShop)}&returnTo=${encodeURIComponent(`/app/billing?plan=${requestedPlan || "STARTER"}`)}`;

      if (isMissingToken || isInvalidToken || isDeprecationError) {
        return {
          success: false,
          needsAuth: true,
          authUrl,
          message: `Shopify store re-authorization required after reinstall. Redirecting to Shopify to authorize and proceed with plan upgrade...`,
        };
      }

      return {
        success: false,
        message: `Failed to create Shopify subscription charge: ${err?.message || "Please verify app permissions."}`,
      };
    }

    return {
      success: false,
      message: "Could not obtain Shopify charge confirmation URL. Please ensure the app is installed from Shopify Admin.",
    };
  }

  return {
    success: true,
    message: "Subscription state refreshed.",
  };
};

export default function BillingPage() {
  const { shop, hasValidToken, authUrl, planInfo, pricingPlansUrl, allConfiguredPlans = [], activePlans = [] } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const submit = useSubmit();

  const currentPlan = planInfo.plan; // FREE | STARTER | PRO
  const isFree = currentPlan === "FREE";
  const isStarter = currentPlan === "STARTER";
  const isPro = currentPlan === "PRO" || currentPlan === "GROWTH";

  // Check which plans are enabled in the SaaS portal
  const activePlanKeys = new Set((activePlans || []).map((p: any) => String(p.planKey || p.name || "").toUpperCase()));
  const isStarterActive = activePlanKeys.has("STARTER");
  const isProActive = activePlanKeys.has("PRO");
  const hasPaidPlansActive = isStarterActive || isProActive;

  const starterPlanObj = (allConfiguredPlans || []).find((p: any) => String(p.planKey || p.name || "").toUpperCase() === "STARTER");
  const proPlanObj = (allConfiguredPlans || []).find((p: any) => String(p.planKey || p.name || "").toUpperCase() === "PRO");
  const freePlanObj = (allConfiguredPlans || []).find((p: any) => String(p.planKey || p.name || "").toUpperCase() === "FREE");
  const starterDisplayName = starterPlanObj?.displayName || "Starter";
  const proDisplayName = proPlanObj?.displayName || "Pro";
  const freeDisplayName = freePlanObj?.displayName || "Free";

  // Auto-redirect top window when authorization is required or confirmation URL is provided
  useEffect(() => {
    const targetUrl = actionData?.confirmationUrl || (actionData?.needsAuth ? actionData?.authUrl : (!hasValidToken ? authUrl : null));
    if (targetUrl) {
      try {
        if (typeof window !== "undefined") {
          if ((window as any).shopify?.open) {
            (window as any).shopify.open(targetUrl, "_top");
          } else if (window.top && window.top !== window) {
            window.top.location.href = targetUrl;
          } else {
            window.location.href = targetUrl;
          }
        }
      } catch (e) {
        console.warn("Automatic top-level redirect error:", e);
      }
    }
  }, [actionData, hasValidToken, authUrl]);

  const handleUpgrade = (plan: "STARTER" | "PRO" | "FREE" | string) => {
    submit({ intent: "subscribe", plan, shop }, { method: "post" });
  };

  const formatDate = (isoString?: string | null) => {
    if (!isoString) return "N/A";
    try {
      return new Date(isoString).toLocaleDateString(undefined, {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    } catch {
      return isoString;
    }
  };

  if (!hasValidToken && authUrl) {
    return (
      <Page>
        <script
          dangerouslySetInnerHTML={{
            __html: `
              try {
                if (window.shopify && window.shopify.open) {
                  window.shopify.open(${JSON.stringify(authUrl)}, "_top");
                } else if (window.top && window.top !== window) {
                  window.top.location.href = ${JSON.stringify(authUrl)};
                } else {
                  window.location.href = ${JSON.stringify(authUrl)};
                }
              } catch (e) {
                window.location.href = ${JSON.stringify(authUrl)};
              }
            `,
          }}
        />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "50vh", gap: "16px", textAlign: "center", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" }}>
          <Text variant="headingMd" as="h2">Connecting to Shopify...</Text>
          <Text tone="subdued" as="p">Authorizing store permissions for {shop}. Please wait...</Text>
        </div>
      </Page>
    );
  }

  return (
    <Page
      title="Shopify App Pricing & Subscription"
      subtitle="Public plans managed securely through Shopify's official hosted billing portal."
      primaryAction={{
        content: "Sync with Shopify",
        onAction: () => submit({ intent: "sync" }, { method: "post" }),
      }}
    >
      <BlockStack gap="500">
        {actionData?.needsAuth && actionData.authUrl && (
          <Banner title="Connecting to Shopify" tone="info">
            <BlockStack gap="200">
              <p>Re-authorizing store permissions for <strong>{shop}</strong>. Redirecting automatically...</p>
            </BlockStack>
          </Banner>
        )}

        {actionData?.confirmationUrl && (
          <Banner title="Approve Plan on Shopify" tone="info">
            <BlockStack gap="200">
              <p>
                Your Shopify plan charge has been created. If the approval page did not open automatically, please click below:
              </p>
              <div>
                <Button
                  variant="primary"
                  url={actionData.confirmationUrl}
                  target="_top"
                >
                  Approve Subscription on Shopify →
                </Button>
              </div>
            </BlockStack>
          </Banner>
        )}

        {actionData?.message && !actionData?.needsAuth && (
          <Banner title={actionData.success ? "Status Update" : "Billing Error"} tone={actionData.success ? "success" : "critical"}>
            <p>{actionData.message}</p>
          </Banner>
        )}

        {/* Cancellation Notice Banner */}
        {planInfo.cancelAtEndOfCycle && (
          <Banner title="Subscription Scheduled for Cancellation" tone="warning">
            <p>
              Your subscription is scheduled to cancel. Current access remains available until:{" "}
              <strong>{formatDate(planInfo.currentBillingCycleEnd)}</strong>.
            </p>
          </Banner>
        )}

        {/* Trial Active Banner */}
        {planInfo.isTrial && (
          <Banner title={`${planInfo.displayName} Free Trial Active`} tone="info">
            <p>
              You are currently enjoying a free trial. Trial ends: <strong>{formatDate(planInfo.trialEndsAt)}</strong>.
            </p>
          </Banner>
        )}

        {/* Developer / Testing 1-Click Plan Switcher for Digi-Horizon Store */}
        {(shop.toLowerCase() === "digi-horizon.myshopify.com" || shop.toLowerCase() === "digi-horizon") && (
          <Card padding="400">
            <BlockStack gap="300">
              <InlineStack align="space-between" blockAlign="center">
                <InlineStack gap="200" align="center">
                  <Badge tone="attention">TEST STORE DEV MODE</Badge>
                  <Text as="p" variant="bodySm" fontWeight="bold">
                    1-Click Plan Switcher (Testing & Verification — $0 Charge)
                  </Text>
                </InlineStack>
                <Text as="p" variant="bodySm" tone="subdued">
                  Current Active Plan: <strong>{currentPlan}</strong>
                </Text>
              </InlineStack>
              <InlineStack gap="200">
                <Button
                  size="slim"
                  variant={isFree ? "secondary" : "primary"}
                  disabled={isFree}
                  onClick={() => submit({ intent: "test_switch", plan: "FREE", shop }, { method: "post" })}
                >
                  {isFree ? "✓ Active: Free Plan ($0)" : "1-Click: Free Plan ($0)"}
                </Button>
                <Button
                  size="slim"
                  variant={isStarter ? "secondary" : "primary"}
                  disabled={isStarter}
                  onClick={() => submit({ intent: "test_switch", plan: "STARTER", shop }, { method: "post" })}
                >
                  {isStarter ? "✓ Active: Starter Plan ($29)" : "1-Click: Starter Plan ($29)"}
                </Button>
                <Button
                  size="slim"
                  variant={isPro ? "secondary" : "primary"}
                  disabled={isPro}
                  onClick={() => submit({ intent: "test_switch", plan: "PRO", shop }, { method: "post" })}
                >
                  {isPro ? "✓ Active: Pro Plan ($79)" : "1-Click: Pro Plan ($79 - AI + BYOK)"}
                </Button>
              </InlineStack>
            </BlockStack>
          </Card>
        )}

        {/* Current Plan Overview Card */}
        <Layout>
          <Layout.Section>
            <Card padding="500">
              <BlockStack gap="400">
                <InlineGrid columns="1fr auto">
                  <InlineStack gap="200" align="start">
                    <FAIcon name="credit-card" style={{ color: "#4F46E5", fontSize: "20px", marginTop: "2px" }} />
                    <BlockStack gap="050">
                      <Text as="h2" variant="headingMd">
                        Current Store Plan
                      </Text>
                      <Text as="p" variant="bodySm" tone="subdued">
                        Canonical status synchronized with Shopify Partner API
                      </Text>
                    </BlockStack>
                  </InlineStack>

                  <InlineStack gap="200">
                    {planInfo.isTrial ? (
                      <Badge tone="attention">TRIAL ACTIVE</Badge>
                    ) : planInfo.cancelAtEndOfCycle ? (
                      <Badge tone="warning">CANCELLING AT CYCLE END</Badge>
                    ) : isFree ? (
                      <Badge tone="info">FREE PLAN</Badge>
                    ) : (
                      <Badge tone="success">ACTIVE</Badge>
                    )}
                  </InlineStack>
                </InlineGrid>

                <Divider />

                <InlineGrid columns={{ xs: 1, md: "2fr 1fr" }} gap="400">
                  <Box padding="400" background="bg-surface-secondary" borderRadius="200" borderWidth="025" borderColor="border">
                    <BlockStack gap="200">
                      <InlineStack align="space-between">
                        <Text as="p" variant="headingLg" fontWeight="bold">
                          {planInfo.displayName.toUpperCase()}
                        </Text>
                        <Text as="p" variant="headingMd" fontWeight="bold" tone="magic">
                          ${planInfo.price}/month
                        </Text>
                      </InlineStack>

                      <Text as="p" variant="bodySm" tone="subdued">
                        {planInfo.description || (isFree
                          ? "Free tier includes essential Shopify catalog integration."
                          : isStarter
                          ? "Starter tier unlocks full Shopify cart and checkout capabilities."
                          : "Pro tier unlocks full conversational AI, recommendations, and BYOK.")}
                      </Text>

                      <Divider />

                      <Box paddingBlock="100">
                        <Text as="p" variant="bodySm" fontWeight="semibold">
                          Active Entitlements:
                        </Text>
                        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: "8px", marginTop: "8px" }}>
                          {(planInfo.features && planInfo.features.length > 0 ? planInfo.features : (isFree ? ["Shopify API catalog integration", "Product search and queries", "Product details and specifications", "No paid subscription required"] : isStarter ? ["Everything in Free", "Shopify Storefront API", "Add to Cart & variant selection", "Cart management & updates", "Shopify Checkout creation", "Promo & discount code validation", "Live shipping rates calculation"] : ["Everything in Starter", "AI sales assistant & AI-powered chatbot", "AI personalized product recommendations", "AI customer support & knowledge base", "OpenAI & Google Gemini integrations", "Store owner's own API keys (BYOK)", "Priority API throughput & analytics"])).map((feat: string, idx: number) => (
                            <div key={idx} style={{ fontSize: "13px", color: "#166534", display: "flex", alignItems: "center", gap: "6px" }}>
                              <FAIcon name="check" style={{ color: "#10B981", fontSize: "12px" }} />
                              <span>{feat}</span>
                            </div>
                          ))}
                        </div>
                      </Box>
                    </BlockStack>
                  </Box>

                  <Box padding="400" background="bg-surface-secondary" borderRadius="200" borderWidth="025" borderColor="border">
                    <BlockStack gap="300">
                      <div>
                        <Text as="p" variant="bodySm" tone="subdued">
                          Billing Cycle
                        </Text>
                        <Text as="p" variant="bodyMd" fontWeight="semibold">
                          {isFree ? "Free (No renewal charges)" : `Next cycle: ${formatDate(planInfo.currentBillingCycleEnd)}`}
                        </Text>
                        {planInfo.lastSubscriptionSync && (
                          <Text as="p" variant="bodySm" tone="subdued">
                            Synced: {formatDate(planInfo.lastSubscriptionSync)}
                          </Text>
                        )}
                      </div>

                      <Divider />

                      <BlockStack gap="200">
                        {isFree && (
                          <>
                            {isStarterActive && (
                              <Button variant="primary" onClick={() => handleUpgrade("STARTER")} fullWidth>
                                Upgrade to {starterDisplayName}
                              </Button>
                            )}
                            {isProActive && (
                              <Button variant={isStarterActive ? "secondary" : "primary"} onClick={() => handleUpgrade("PRO")} fullWidth>
                                Upgrade to {proDisplayName}
                              </Button>
                            )}
                            {!hasPaidPlansActive && (
                              <Box padding="200" background="bg-surface-secondary" borderRadius="100">
                                <Text as="p" variant="bodySm" tone="subdued" alignment="center">
                                  Paid upgrade tiers are currently disabled or pending Shopify App Store review approval.
                                </Text>
                              </Box>
                            )}
                          </>
                        )}
                        {isStarter && (
                          <>
                            {isProActive && (
                              <Button variant="primary" onClick={() => handleUpgrade("PRO")} fullWidth>
                                Upgrade to {proDisplayName}
                              </Button>
                            )}
                            <Button variant="secondary" onClick={() => handleUpgrade("FREE")} fullWidth>
                              Revert / Downgrade to {freeDisplayName} Plan
                            </Button>
                          </>
                        )}
                        {isPro && (
                          <>
                            {isStarterActive && (
                              <Button variant="secondary" onClick={() => handleUpgrade("STARTER")} fullWidth>
                                Downgrade to {starterDisplayName}
                              </Button>
                            )}
                            <Button variant="secondary" onClick={() => handleUpgrade("FREE")} fullWidth>
                              Revert / Downgrade to {freeDisplayName} Plan
                            </Button>
                          </>
                        )}

                        <Form method="post">
                          <input type="hidden" name="intent" value="sync" />
                          <Button submit variant="plain" size="micro" fullWidth>
                            Sync with Shopify
                          </Button>
                        </Form>
                      </BlockStack>
                    </BlockStack>
                  </Box>
                </InlineGrid>
              </BlockStack>
            </Card>
          </Layout.Section>

          {/* Public Plans Grid - Dynamically filtered to ONLY plans marked active/enabled in SaaS portal */}
          <Layout.Section>
            <InlineStack align="space-between" blockAlign="center">
              <Text as="h2" variant="headingMd">
                Available Public Plans
              </Text>
              <Badge tone={hasPaidPlansActive ? "success" : "attention"}>
                {hasPaidPlansActive ? `${activePlans.length} Active Plan${activePlans.length === 1 ? "" : "s"}` : "Paid Plans Pending Review"}
              </Badge>
            </InlineStack>

            {!hasPaidPlansActive && (
              <Box paddingBlockStart="200">
                <Banner title="Additional Subscription Tiers Pending Shopify App Review" tone="info">
                  <p>
                    Starter and Pro plans are disabled during the initial Shopify App Store review. Once our app review is approved and published, paid tiers will be enabled in the portal and automatically appear here.
                  </p>
                </Banner>
              </Box>
            )}

            <Box paddingBlockStart="300">
              <InlineGrid columns={{ xs: 1, sm: 1, md: activePlans.length === 1 ? 1 : activePlans.length === 2 ? 2 : 3 }} gap="400">
                {activePlans.map((plan: any) => {
                  const pKey = String(plan.planKey || plan.name || "").toUpperCase();
                  const isCurrent = currentPlan === pKey;
                  const iconName = pKey === "PRO" ? "wand-magic-sparkles" : pKey === "STARTER" ? "cart-shopping" : "cube";
                  const iconColor = pKey === "PRO" ? "#F59E0B" : pKey === "STARTER" ? "#4F46E5" : "#64748B";

                  return (
                    <Card key={plan.id || pKey} padding="500">
                      <BlockStack gap="400">
                        <BlockStack gap="100">
                          <InlineStack align="space-between">
                            <InlineStack gap="200" align="center">
                              <FAIcon name={iconName} style={{ color: iconColor, fontSize: "18px" }} />
                              <Text as="h3" variant="headingSm">
                                {plan.displayName || pKey}
                              </Text>
                            </InlineStack>
                            {isCurrent && <Badge tone="info">Current Plan</Badge>}
                          </InlineStack>
                          <Text as="p" variant="headingXl" fontWeight="bold">
                            ${plan.price}
                            <Text as="span" variant="bodySm" tone="subdued">
                              /{plan.billingInterval === "ONE_TIME" ? "one-time" : "month"}
                            </Text>
                          </Text>
                        </BlockStack>

                        <Text as="p" variant="bodySm" tone="subdued">
                          {plan.description || "Plan features and capabilities"}
                        </Text>

                        <Divider />

                        <Box paddingBlock="100">
                          <Text as="p" variant="bodySm" fontWeight="semibold">
                            Includes:
                          </Text>
                          <div style={{ display: "flex", flexDirection: "column", gap: "6px", marginTop: "8px" }}>
                            {(plan.features || []).map((f: string, idx: number) => (
                              <div key={idx} style={{ fontSize: "13px", color: "#374151", display: "flex", alignItems: "flex-start", gap: "8px", lineHeight: "1.4" }}>
                                <FAIcon name="circle-check" style={{ color: "#10B981", fontSize: "14px", marginTop: "2px", flexShrink: 0 }} />
                                <span>{f}</span>
                              </div>
                            ))}
                          </div>
                        </Box>

                        {pKey === "FREE" ? (
                          <Button
                            variant={isCurrent ? "secondary" : "primary"}
                            disabled={isCurrent}
                            onClick={() => handleUpgrade("FREE")}
                            fullWidth
                          >
                            {isCurrent ? "Current Plan" : "Switch / Revert to Free"}
                          </Button>
                        ) : (
                          <Button
                            variant={isCurrent ? "secondary" : "primary"}
                            disabled={isCurrent}
                            onClick={() => handleUpgrade(pKey as any)}
                            fullWidth
                          >
                            {isCurrent ? "Current Plan" : `Upgrade to ${plan.displayName || pKey}`}
                          </Button>
                        )}
                      </BlockStack>
                    </Card>
                  );
                })}
              </InlineGrid>
            </Box>

            {/* Store Owner BYOK Notice */}
            {isProActive && (
              <Box paddingBlockStart="300">
                <Banner title="Bring Your Own API Key (BYOK) for AI Features" tone="info">
                  <p>
                    Pro plan merchants configure their own OpenAI or Google Gemini API keys in Settings. Our application never imposes artificial message quotas or extra usage fees.
                  </p>
                </Banner>
              </Box>
            )}
          </Layout.Section>

          {/* Comparison Feature Matrix Table */}
          <Layout.Section>
            <Card padding="500">
              <BlockStack gap="400">
                <BlockStack gap="100">
                  <Text as="h2" variant="headingMd">
                    <FAIcon name="table-columns" style={{ color: "#4F46E5", marginRight: "8px" }} /> Plan Feature Matrix & Entitlements
                  </Text>
                  <Text as="p" variant="bodySm" tone="subdued">
                    Features and API access are strictly authorized and enforced on the server.
                  </Text>
                </BlockStack>

                <div style={{ overflowX: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left", fontSize: "14px" }}>
                    <thead>
                      <tr style={{ borderBottom: "2px solid #E5E7EB" }}>
                        <th style={{ padding: "12px 16px", fontWeight: "600" }}>Feature</th>
                        <th style={{ padding: "12px 16px", fontWeight: "600", textAlign: "center" }}>
                          {freeDisplayName} (${freePlanObj?.price ?? 0}/mo)
                        </th>
                        <th style={{ padding: "12px 16px", fontWeight: "600", textAlign: "center" }}>
                          {starterDisplayName} (${starterPlanObj?.price ?? 29}/mo)
                        </th>
                        <th style={{ padding: "12px 16px", fontWeight: "600", textAlign: "center" }}>
                          {proDisplayName} (${proPlanObj?.price ?? 79}/mo)
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {FEATURE_MATRIX_ROWS.map((row, idx) => (
                        <tr
                          key={idx}
                          style={{
                            borderBottom: "1px solid #F3F4F6",
                            backgroundColor: idx % 2 === 0 ? "#FFFFFF" : "#F9FAFB",
                          }}
                        >
                          <td style={{ padding: "10px 16px", fontWeight: "500" }}>{row.feature}</td>
                          <td style={{ padding: "10px 16px", textAlign: "center" }}>
                            {typeof row.free === "string" ? (
                              <strong>{row.free}</strong>
                            ) : row.free ? (
                              <span style={{ color: "#10B981", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-check" /> YES
                              </span>
                            ) : (
                              <span style={{ color: "#EF4444", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-xmark" /> NO
                              </span>
                            )}
                          </td>
                          <td style={{ padding: "10px 16px", textAlign: "center" }}>
                            {typeof row.starter === "string" ? (
                              <span>{row.starter}</span>
                            ) : row.starter ? (
                              <span style={{ color: "#10B981", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-check" /> YES
                              </span>
                            ) : (
                              <span style={{ color: "#EF4444", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-xmark" /> NO
                              </span>
                            )}
                          </td>
                          <td style={{ padding: "10px 16px", textAlign: "center" }}>
                            {typeof row.pro === "string" ? (
                              <strong>{row.pro}</strong>
                            ) : row.pro ? (
                              <span style={{ color: "#10B981", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-check" /> YES
                              </span>
                            ) : (
                              <span style={{ color: "#EF4444", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                <FAIcon name="circle-xmark" /> NO
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </BlockStack>
            </Card>
          </Layout.Section>
        </Layout>
      </BlockStack>
    </Page>
  );
}
