import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, Form, useSearchParams, Link, useNavigate, useActionData, useNavigation, redirect, useFetcher, useRouteError } from "react-router";
import {
  getAdminDashboardData,
  exportStoresCSV,
  exportCustomersCSV,
  exportTransactionsCSV,
  exportRevenueCSV,
  getRevenueAnalytics,
  getCustomersData,
  getTransactionsData,
  getTransactionDetail,
  getGlobalSearch,
  createStore,
  updateStore,
  updateSubscription,
  getAdminNotifications,
  clearAllAdminNotifications,
  getSessionAnalyticsData,
  getAdminPlansData,
  createAdminPlan,
  updateAdminPlan,
  deleteAdminPlan,
  getAdminHelplinesData,
  createAdminHelpline,
  updateAdminHelpline,
  deleteAdminHelpline,
  toggleAdminHelplineStatus,
  toggleStoreChatbotAdmin,
} from "../services/admin.server";
import {
  getNotifications,
  getUnreadCount,
  markNotificationAsRead,
  markAllNotificationsAsRead,
} from "../services/notification.server";
import {
  getAIIntegrationSettings,
  saveAIIntegrationSettings,
  testAIProviderConnection,
  getDynamicAIProviders,
  type SystemIntegrationsData,
} from "../services/ai-config.server";
import {
  authenticateAdminRequest,
  verifyAdminPassword,
  createAdminSessionToken,
  getAdminSessionCookieHeader,
  getAdminLogoutCookieHeader,
  checkLoginRateLimit,
} from "../services/admin-auth.server";
import { getPlatformSettings, savePlatformSettings, getDefaultStoreDomainSync } from "../services/platform-settings.server";
import { adminAdjustCredits, getAvailableCredits } from "../services/credit-ledger.server";
import { registerShop } from "../services/shop.server";
import prisma from "../db.server";
import { useState, useEffect, useRef } from "react";
import FAIcon from "../components/FAIcon";


export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const unmask = url.searchParams.get("unmask") === "true";

  const authResult = authenticateAdminRequest(request);

  if (!authResult.isAuthenticated) {
    return { isAuthenticated: false as const };
  }

  const view = url.searchParams.get("view") || (url.searchParams.get("storeId") ? "store_details" : url.searchParams.get("txId") ? "transaction_details" : "dashboard");
  const search = url.searchParams.get("search") || "";
  const planFilter = url.searchParams.get("planFilter") || "ALL";
  const statusFilter = url.searchParams.get("statusFilter") || "ALL";
  const typeFilter = url.searchParams.get("typeFilter") || "ALL";
  const eventTypeFilter = url.searchParams.get("eventTypeFilter") || "ALL";
  const sortBy = url.searchParams.get("sortBy") || "date";
  const sortDir = url.searchParams.get("sortDir") || "desc";
  const timeframe = url.searchParams.get("timeframe") || "30d";
  const page = parseInt(url.searchParams.get("page") || "1", 10);
  const pageSize = parseInt(url.searchParams.get("pageSize") || "10", 10);
  const selectedStoreId = url.searchParams.get("storeId") || "";
  const selectedTxId = url.searchParams.get("txId") || "";

  try {
    let adminData = await getAdminDashboardData({
      search,
      planFilter,
      statusFilter,
      sortBy,
      page,
      pageSize,
      selectedStoreId,
      unmask,
    });

    const totalDbStores = await prisma.shop.count();
    if (totalDbStores === 0) {
      await registerShop({
        shopifyDomain: getDefaultStoreDomainSync(),
        accessToken: "shpss_sample_token",
        scopes: "read_products,read_content",
      });

      adminData = await getAdminDashboardData({
        search,
        planFilter,
        statusFilter,
        sortBy,
        page,
        pageSize,
        selectedStoreId,
        unmask,
      });
    }

    const revenueData = await getRevenueAnalytics(timeframe);
    const customersData = await getCustomersData({ search, page, pageSize, unmask });
    const transactionsData = await getTransactionsData({
      search,
      statusFilter,
      eventTypeFilter,
      sortBy,
      sortDir,
      page,
      pageSize,
      unmask,
    });
    const selectedTxDetail = selectedTxId ? await getTransactionDetail(selectedTxId, unmask) : null;
    const searchResults = search ? await getGlobalSearch(search) : { stores: [], customers: [], transactions: [] };
    const {
      notificationsList,
      unreadCount: unreadNotificationCount,
      totalCount: totalNotificationsCount,
      totalPages: totalNotificationsPages,
      page: notificationsPage,
    } = await getAdminNotifications({ search, statusFilter, typeFilter, page, pageSize });
    const sessionAnalytics = await getSessionAnalyticsData();

    const targetShop = adminData.selectedStoreDetail?.store || adminData.storesData.stores[0];
    let targetShopId = selectedStoreId || targetShop?.id || "";

    if (!targetShopId && prisma?.shop && typeof prisma.shop.findFirst === "function") {
      const firstShop = await prisma.shop.findFirst().catch(() => null);
      if (firstShop) targetShopId = firstShop.id;
    }

    const integrationSettings = await getAIIntegrationSettings(targetShopId || "global");
    const dynamicProviders = getDynamicAIProviders();
    const platformSettings = await getPlatformSettings();
    const adminPlans = await getAdminPlansData();
    const adminHelplines = await getAdminHelplinesData();

    console.log("[SaaS Admin Loader] Fetched stores count:", adminData.storesData.totalCount, "KPIs:", adminData.kpis, "Plans count:", adminPlans.length, "Helplines count:", adminHelplines.length);

    return {
      isAuthenticated: true as const,
      unmask,
      adminKPIs: adminData.kpis,
      adminStoresData: adminData.storesData,
      selectedStoreDetail: adminData.selectedStoreDetail,
      revenueData,
      customersData,
      transactionsData,
      selectedTxDetail,
      searchResults,
      notificationsList,
      unreadNotificationCount,
      totalNotificationsCount,
      totalNotificationsPages,
      notificationsPage,
      sessionAnalytics,
      integrationSettings,
      dynamicProviders,
      platformSettings,
      adminPlans,
      adminHelplines,
      targetShopId: targetShopId || "global",
      search,
      planFilter,
      statusFilter,
      typeFilter,
      eventTypeFilter,
      sortBy,
      sortDir,
      timeframe,
      page,
      pageSize,
      view,
      selectedTxId,
      selectedStoreId,
    };
  } catch (e) {
    console.error("SaaS Admin loader error:", e);
    const dynamicProviders = getDynamicAIProviders();
    let integrationSettings: SystemIntegrationsData | null = null;
    try {
      integrationSettings = await getAIIntegrationSettings();
    } catch {
      integrationSettings = {
        aiProvider: "openai",
        openaiApiKeyMasked: "",
        openaiModel: "gpt-4o-mini",
        openaiTemperature: 0.7,
        openaiMaxTokens: 1000,
        openaiEnabled: true,
        openaiHasKey: false,
        geminiApiKeyMasked: "",
        geminiModel: "gemini-3.6-flash",
        geminiTemperature: 0.7,
        geminiMaxTokens: 1000,
        geminiEnabled: true,
        geminiHasKey: false,
      };
    }

    let fallbackHelplines: any[] = [];
    try {
      fallbackHelplines = await getAdminHelplinesData();
    } catch {
      fallbackHelplines = [];
    }

    return {
      isAuthenticated: true as const,
      unmask: false,
      adminKPIs: {
        totalStores: 0,
        activeStores: 0,
        uninstalledStores: 0,
        trialStores: 0,
        oneTimeRevenue: 0,
        starterMrr: 0,
        proMrr: 0,
        mrr: 0,
        arr: 0,
        arpu: 0,
        planBreakdown: { FREE: 0, STARTER: 0, GROWTH: 0, PRO: 0 },
      },
      adminStoresData: { stores: [], totalCount: 0, page: 1, totalPages: 1 },
      selectedStoreDetail: null,
      revenueData: { oneTimeRevenue: 0, starterMrr: 0, proMrr: 0, mrr: 0, arr: 0, growthRate: 0, points: [] },
      customersData: { customers: [], allCustomers: [], totalCount: 0, page: 1, totalPages: 1 },
      transactionsData: { transactions: [], allTransactions: [], totalCount: 0, page: 1, pageSize: 10, totalPages: 1 },
      selectedTxDetail: null,
      searchResults: { stores: [], customers: [], transactions: [] },
      notificationsList: [],
      unreadNotificationCount: 0,
      totalNotificationsCount: 0,
      totalNotificationsPages: 1,
      notificationsPage: 1,
      sessionAnalytics: { totalSessions: 0, totalMessages: 0, assistedSessions: 0, knowledgeCount: 0, conversionRate: 0, avgMessagesPerSession: 0 },
      integrationSettings,
      dynamicProviders,
      platformSettings: await getPlatformSettings().catch(() => ({ defaultStoreDomain: getDefaultStoreDomainSync(), appHandle: process.env.SHOPIFY_APP_HANDLE_PRICE || "commercebot-ai", partnerDashboardUrl: process.env.SHOPIFY_PARTNER_DASHBOARD_URL || "", partnerStoreUrl: process.env.SHOPIFY_PARTNER_STORE_URL || "", appStoreListingUrl: process.env.SHOPIFY_APP_STORE_URL || "", appProductionUrl: process.env.SHOPIFY_APP_URL || "" })),
      adminPlans: [],
      adminHelplines: fallbackHelplines,
      targetShopId: "global",
      search: "",
      planFilter: "ALL",
      statusFilter: "ALL",
      typeFilter: "ALL",
      eventTypeFilter: "ALL",
      sortBy: "date",
      sortDir: "desc",
      timeframe: "30d",
      page: 1,
      pageSize: 10,
      view,
      selectedTxId: "",
      selectedStoreId: "",
    };
  }
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const formData = await request.formData();
  const intent = String(formData.get("_intent") || "");
  const authResult = authenticateAdminRequest(request);

  if (intent === "admin_login") {
    try {
      checkLoginRateLimit(authResult.clientIp);
    } catch (err: any) {
      return { success: false, message: err.message };
    }

    const password = String(formData.get("password") || "").trim();
    if (verifyAdminPassword(password)) {
      const sessionToken = createAdminSessionToken();
      
      if (prisma?.shop && typeof prisma.shop.findFirst === "function") {
        const firstShop = await prisma.shop.findFirst().catch(() => null);
        if (firstShop && prisma?.auditLog && typeof prisma.auditLog.create === "function") {
          await prisma.auditLog.create({
            data: {
              shopId: firstShop.id,
              action: "Admin Logged In",
              resource: `IP: ${authResult.clientIp}`,
              status: "SUCCESS",
            },
          }).catch(() => {});
        }
      }

      const requestUrl = new URL(request.url);
      const cleanPath = requestUrl.pathname.replace(/\.data$/, "");
      const host = request.headers.get("x-forwarded-host") || request.headers.get("host") || requestUrl.host;
      const isHttps = !host.includes("localhost") && !host.includes("127.0.0.1") ? true : (request.headers.get("x-forwarded-proto") === "https" || requestUrl.protocol === "https:");
      const redirectUrl = `${isHttps ? "https" : "http"}://${host}${cleanPath}${requestUrl.search}`;

      return redirect(redirectUrl, {
        headers: {
          "Set-Cookie": getAdminSessionCookieHeader(sessionToken),
        },
      });
    }

    return { success: false, message: "Invalid administrator credentials." };
  }

  if (intent === "admin_logout") {
    const requestUrl = new URL(request.url);
    const cleanPath = requestUrl.pathname.replace(/\.data$/, "");
    const host = request.headers.get("x-forwarded-host") || request.headers.get("host") || requestUrl.host;
    const isHttps = !host.includes("localhost") && !host.includes("127.0.0.1") ? true : (request.headers.get("x-forwarded-proto") === "https" || requestUrl.protocol === "https:");
    const redirectUrl = `${isHttps ? "https" : "http"}://${host}${cleanPath}${requestUrl.search}`;

    return redirect(redirectUrl, {
      headers: {
        "Set-Cookie": getAdminLogoutCookieHeader(),
      },
    });
  }

  if (!authResult.isAuthenticated) {
    return new Response(JSON.stringify({ error: "Unauthorized admin request" }), {
      status: 401,
      headers: { "Content-Type": "application/json" },
    });
  }

  try {
    const url = new URL(request.url);
    const unmask = url.searchParams.get("unmask") === "true";
    const dateStr = new Date().toISOString().split("T")[0];

    if (intent === "export_stores_csv" || intent === "export_csv") {
      const csvContent = await exportStoresCSV(unmask);
      return new Response(csvContent, {
        status: 200,
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": `attachment; filename="stores-${dateStr}.csv"`,
        },
      });
    }

    if (intent === "export_customers_csv") {
      const csvContent = await exportCustomersCSV(unmask);
      return new Response(csvContent, {
        status: 200,
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": `attachment; filename="customers-${dateStr}.csv"`,
        },
      });
    }

    if (intent === "export_transactions_csv") {
      const csvContent = await exportTransactionsCSV(unmask);
      return new Response(csvContent, {
        status: 200,
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": `attachment; filename="transactions-${dateStr}.csv"`,
        },
      });
    }

    if (intent === "export_revenue_csv") {
      const csvContent = await exportRevenueCSV();
      return new Response(csvContent, {
        status: 200,
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": `attachment; filename="revenue-${dateStr}.csv"`,
        },
      });
    }

    if (intent === "save_platform_settings") {
      const defaultStoreDomain = String(formData.get("defaultStoreDomain") || "").trim();
      const appHandle = String(formData.get("appHandle") || "").trim();
      const partnerDashboardUrl = String(formData.get("partnerDashboardUrl") || "").trim();
      const partnerStoreUrl = String(formData.get("partnerStoreUrl") || "").trim();
      const appStoreListingUrl = String(formData.get("appStoreListingUrl") || "").trim();
      const appProductionUrl = String(formData.get("appProductionUrl") || "").trim();

      const updated = await savePlatformSettings({
        defaultStoreDomain,
        appHandle,
        partnerDashboardUrl,
        partnerStoreUrl,
        appStoreListingUrl,
        appProductionUrl,
      });

      return {
        success: true,
        intent: "save_platform_settings",
        message: `Primary Store & Shopify Partner configuration updated successfully! Default domain set to "${updated.defaultStoreDomain}" and app handle set to "${updated.appHandle}".`,
      };
    }


    if (intent === "admin_adjust_credits") {
      const shopId = String(formData.get("shopId") || "");
      const amount = parseInt(String(formData.get("amount") || "0"), 10);
      const reason = String(formData.get("reason") || "Customer support credit adjustment").trim();

      if (!shopId || isNaN(amount) || amount === 0) {
        return { success: false, message: "Valid store and non-zero adjustment amount required." };
      }

      const res = await adminAdjustCredits({ shopId, amount, reason, adminId: "saas_admin" });
      return {
        success: true,
        message: `Successfully adjusted store credits by ${amount > 0 ? "+" : ""}${amount}! New available balance: ${res.newBalance.toLocaleString()} credits.`,
      };
    }

    if (intent === "create_store") {
      const shopifyDomain = String(formData.get("shopifyDomain") || "");
      const merchantEmail = String(formData.get("merchantEmail") || "");
      const merchantName = String(formData.get("merchantName") || "");
      const plan = (String(formData.get("plan") || "STARTER")) as any;

      if (!shopifyDomain) {
        return { success: false, message: "Shopify store domain is required." };
      }

      await createStore({ shopifyDomain, merchantEmail, merchantName, plan });
      return { success: true, intent: "create_store", message: `Store ${shopifyDomain} successfully onboarded in database!` };
    }

    if (intent === "edit_store") {
      const shopId = String(formData.get("shopId") || "");
      const shopifyDomain = String(formData.get("shopifyDomain") || "");
      const merchantEmail = String(formData.get("merchantEmail") || "");
      const merchantName = String(formData.get("merchantName") || "");
      const status = String(formData.get("status") || "ACTIVE") as any;
      const rawChatbotAdminStatus = formData.get("chatbotAdminStatus");
      const chatbotAdminDisabled = rawChatbotAdminStatus !== null
        ? (rawChatbotAdminStatus === "INACTIVE" || rawChatbotAdminStatus === "true")
        : undefined;

      if (!shopId) return { success: false, message: "Shop ID is required." };

      await updateStore(shopId, { shopifyDomain, merchantEmail, merchantName, status, chatbotAdminDisabled });
      return { success: true, intent: "edit_store", message: `Store settings updated successfully!` };
    }

    if (intent === "toggle_store_chatbot") {
      const shopId = String(formData.get("shopId") || "");
      const adminDisabled = formData.get("adminDisabled") === "true";
      if (!shopId) return { success: false, message: "Shop ID is required." };

      await toggleStoreChatbotAdmin(shopId, adminDisabled);
      return {
        success: true,
        intent: "toggle_store_chatbot",
        message: adminDisabled
          ? "Store chatbot has been deactivated by SaaS Admin (merchant cannot enable)."
          : "Store chatbot has been activated by SaaS Admin (merchant can now enable/disable).",
      };
    }

    if (intent === "update_subscription") {
      const shopId = String(formData.get("shopId") || "");
      const plan = (String(formData.get("plan") || "STARTER")) as any;
      const status = String(formData.get("status") || "ACTIVE") as any;
      const monthlyLimit = parseInt(String(formData.get("monthlyLimit") || "1000"), 10);

      if (!shopId) return { success: false, message: "Shop ID is required." };

      await updateSubscription(shopId, { plan, status, monthlyLimit });
      return { success: true, intent: "update_subscription", message: `Local Subscription database updated to ${plan} plan!` };
    }

    if (intent === "create_plan") {
      const planKey = String(formData.get("planKey") || "");
      const displayName = String(formData.get("displayName") || "");
      const price = parseFloat(String(formData.get("price") || "0"));
      const billingInterval = String(formData.get("billingInterval") || "MONTHLY") as any;
      const billingType = billingInterval === "ONE_TIME" ? "ONE_TIME" : "RECURRING";
      const aiUsageEnabled = formData.get("aiUsageEnabled") === "true" || formData.get("aiUsageEnabled") === "on";
      const aiMonthlyLimit = aiUsageEnabled ? parseInt(String(formData.get("aiMonthlyLimit") || "25000"), 10) : null;
      const monthlyLimit = aiMonthlyLimit || 0;
      const description = String(formData.get("description") || "");
      const rawFeatures = String(formData.get("features") || "");
      const features = rawFeatures.split("\n").map((s) => s.trim()).filter(Boolean);
      const isActive = formData.get("isActive") !== "false" && formData.get("isActive") !== "off";

      await createAdminPlan({
        planKey,
        displayName,
        price,
        billingType,
        billingInterval,
        aiUsageEnabled,
        aiMonthlyLimit,
        monthlyLimit,
        description,
        features,
        isActive,
      });

      return { success: true, intent: "create_plan", message: `Plan ${displayName || planKey} created successfully!` };
    }

    if (intent === "edit_plan") {
      const planId = String(formData.get("planId") || formData.get("planKey") || formData.get("id") || "");
      const displayName = String(formData.get("displayName") || "");
      const price = parseFloat(String(formData.get("price") || "0"));
      const billingInterval = String(formData.get("billingInterval") || "MONTHLY") as any;
      const billingType = billingInterval === "ONE_TIME" ? "ONE_TIME" : "RECURRING";
      const aiUsageEnabled = formData.get("aiUsageEnabled") === "true" || formData.get("aiUsageEnabled") === "on";
      const aiMonthlyLimit = aiUsageEnabled ? parseInt(String(formData.get("aiMonthlyLimit") || "25000"), 10) : null;
      const monthlyLimit = aiMonthlyLimit || 0;
      const description = String(formData.get("description") || "");
      const rawFeatures = String(formData.get("features") || "");
      const features = rawFeatures.split("\n").map((s) => s.trim()).filter(Boolean);
      const isActive = formData.get("isActive") === "true" || formData.get("isActive") === "on";

      await updateAdminPlan(planId, {
        displayName,
        price,
        billingType,
        billingInterval,
        aiUsageEnabled,
        aiMonthlyLimit,
        monthlyLimit,
        description,
        features,
        isActive,
      });

      return { success: true, intent: "edit_plan", message: `Plan updated successfully!` };
    }

    if (intent === "delete_plan") {
      const planId = String(formData.get("planId") || formData.get("planKey") || formData.get("id") || "");
      await deleteAdminPlan(planId);
      return { success: true, intent: "delete_plan", message: `Plan deleted successfully from database!` };
    }

    if (intent === "toggle_plan_status") {
      const planId = String(formData.get("planId") || formData.get("planKey") || formData.get("id") || "");
      const isActive = formData.get("isActive") === "true";
      await updateAdminPlan(planId, { isActive });
      return { success: true, intent: "toggle_plan_status", message: `Plan status updated!` };
    }

    if (intent === "change_store_plan") {
      const shopId = String(formData.get("shopId") || "");
      const newPlan = String(formData.get("plan") || "FREE").toUpperCase() as any;
      const { SubscriptionService } = await import("../services/subscription.server");
      await SubscriptionService.changePlan({ shopId, newPlan });
      return { success: true, intent: "change_store_plan", message: `Store plan updated to ${newPlan} successfully!` };
    }

    if (intent === "update_store_token") {
      const shopId = String(formData.get("shopId") || "");
      const accessToken = String(formData.get("accessToken") || "").trim();
      if (!shopId || !accessToken) {
        return { success: false, message: "Shop ID and Access Token are required." };
      }
      const { registerShop } = await import("../services/shop.server");
      const shopRecord = await prisma.shop.findUnique({ where: { id: shopId } });
      if (!shopRecord) {
        return { success: false, message: "Shop not found." };
      }
      await registerShop({
        shopifyDomain: shopRecord.shopifyDomain,
        accessToken,
        scopes: shopRecord.scopes || "read_products,read_content,read_orders,write_orders",
        isReinstall: true,
      });
      return { success: true, intent: "update_store_token", message: `Access token updated for ${shopRecord.shopifyDomain}!` };
    }

    if (intent === "create_helpline") {
      const department = String(formData.get("department") || "").trim();
      const phoneNumber = String(formData.get("phoneNumber") || "").trim();
      const email = String(formData.get("email") || "").trim();
      const hours = String(formData.get("hours") || "24/7 Support").trim();
      const description = String(formData.get("description") || "").trim();
      const sortOrder = parseInt(String(formData.get("sortOrder") || "0"), 10);
      const isActive = formData.get("isActive") !== "false" && formData.get("isActive") !== "off";

      if (!department || !phoneNumber || !email) {
        return { success: false, message: "Department name, phone number, and email are required." };
      }

      await createAdminHelpline({
        department,
        phoneNumber,
        email,
        hours,
        description,
        sortOrder,
        isActive,
      });

      return { success: true, intent: "create_helpline", message: `Helpline for ${department} created successfully!` };
    }

    if (intent === "edit_helpline") {
      const helplineId = String(formData.get("helplineId") || formData.get("id") || "");
      const department = String(formData.get("department") || "").trim();
      const phoneNumber = String(formData.get("phoneNumber") || "").trim();
      const email = String(formData.get("email") || "").trim();
      const hours = String(formData.get("hours") || "24/7 Support").trim();
      const description = String(formData.get("description") || "").trim();
      const sortOrder = parseInt(String(formData.get("sortOrder") || "0"), 10);
      const isActive = formData.get("isActive") === "true" || formData.get("isActive") === "on";

      if (!helplineId) return { success: false, message: "Helpline ID is required." };

      await updateAdminHelpline(helplineId, {
        department,
        phoneNumber,
        email,
        hours,
        description,
        sortOrder,
        isActive,
      });

      return { success: true, intent: "edit_helpline", message: `Helpline updated successfully!` };
    }

    if (intent === "delete_helpline") {
      const helplineId = String(formData.get("helplineId") || formData.get("id") || "");
      await deleteAdminHelpline(helplineId);
      return { success: true, intent: "delete_helpline", message: `Helpline deleted successfully!` };
    }

    if (intent === "toggle_helpline_status") {
      const helplineId = String(formData.get("helplineId") || formData.get("id") || "");
      const isActive = formData.get("isActive") === "true";
      await toggleAdminHelplineStatus(helplineId, isActive);
      return { success: true, intent: "toggle_helpline_status", message: `Helpline status updated!` };
    }

    if (intent === "sync_store_subscription") {
      const targetStoreId = String(formData.get("storeId") || formData.get("shopId") || "");
      const { BillingService } = await import("../services/billing.server");
      const planInfo = await BillingService.syncSubscription(targetStoreId);
      return { success: true, intent: "sync_store_subscription", message: `Successfully synced subscription from Shopify Partner API: ${planInfo.displayName} (${planInfo.status}).` };
    }

    let shopId = String(formData.get("shopId") || "global");

    if (intent === "save_global_provider") {
      const aiProvider = String(formData.get("aiProvider") || "openai");
      await saveAIIntegrationSettings(shopId, { aiProvider });
      return { success: true, intent, message: `Active AI Engine Provider updated to ${aiProvider === "gemini" ? "Google Gemini" : "OpenAI"}!` };
    }

    if (intent === "save_openai_config") {
      const rawApiKey = formData.get("openaiApiKey");
      const openaiApiKey = rawApiKey !== null ? String(rawApiKey) : undefined;
      const openaiModel = String(formData.get("openaiModel") || "gpt-4o-mini");
      const openaiTemperature = parseFloat(String(formData.get("openaiTemperature") || "0.7"));
      const openaiMaxTokens = parseInt(String(formData.get("openaiMaxTokens") || "1000"), 10);
      const openaiEnabled = formData.get("openaiEnabled") === "true";

      await saveAIIntegrationSettings(shopId, {
        ...(openaiApiKey !== undefined ? { openaiApiKey } : {}),
        openaiModel,
        openaiTemperature,
        openaiMaxTokens,
        openaiEnabled,
      });
      return { success: true, intent, message: "OpenAI integration configuration saved successfully!" };
    }

    if (intent === "save_gemini_config") {
      const rawApiKey = formData.get("geminiApiKey");
      const geminiApiKey = rawApiKey !== null ? String(rawApiKey) : undefined;
      const geminiModel = String(formData.get("geminiModel") || "gemini-1.5-flash");
      const geminiTemperature = parseFloat(String(formData.get("geminiTemperature") || "0.7"));
      const geminiMaxTokens = parseInt(String(formData.get("geminiMaxTokens") || "1000"), 10);
      const geminiEnabled = formData.get("geminiEnabled") === "true";

      await saveAIIntegrationSettings(shopId, {
        ...(geminiApiKey !== undefined ? { geminiApiKey } : {}),
        geminiModel: geminiModel === "gemini-3.6-flash" ? "gemini-1.5-flash" : geminiModel,
        geminiTemperature,
        geminiMaxTokens,
        geminiEnabled,
      });
      return { success: true, intent, message: "Google Gemini integration configuration saved successfully!" };
    }

    if (intent === "test_connection_openai" || (intent === "test_connection" && formData.get("provider") === "openai")) {
      const apiKey = String(formData.get("openaiApiKey") || formData.get("apiKey") || "");
      const model = String(formData.get("openaiModel") || formData.get("model") || "gpt-4o-mini");
      const testRes = await testAIProviderConnection(shopId, "openai", apiKey, model);
      return { testResult: { provider: "openai", ...testRes }, intent };
    }

    if (intent === "test_connection_gemini" || (intent === "test_connection" && formData.get("provider") === "gemini")) {
      const apiKey = String(formData.get("geminiApiKey") || formData.get("apiKey") || "");
      const model = String(formData.get("geminiModel") || formData.get("model") || "gemini-3.6-flash");
      const testRes = await testAIProviderConnection(shopId, "gemini", apiKey, model);
      return { testResult: { provider: "gemini", ...testRes }, intent };
    }

    if (intent === "mark_notification_read" || intent === "mark_read") {
      const id = String(formData.get("id") || formData.get("notificationId") || "");
      if (!id) {
        return { success: false, message: "Missing notification ID" };
      }
      await markNotificationAsRead(id, "global");
      const unreadCount = await getUnreadCount("global");
      return { success: true, intent: "mark_notification_read", notificationId: id, unreadCount, message: "Notification marked as read." };
    }

    if (intent === "mark_all_notifications_read" || intent === "mark_all_read" || intent === "read_all") {
      await markAllNotificationsAsRead("global");
      return { success: true, intent: "mark_all_notifications_read", unreadCount: 0, message: "All notifications marked as read" };
    }

    if (intent === "clear_notifications") {
      await clearAllAdminNotifications();
      return { success: true, intent, message: "System audit logs & notifications cleared successfully." };
    }
  } catch (err: any) {
    return { success: false, intent, message: err.message || "An unexpected error occurred." };
  }

  return null;
};

// DYNAMIC REVENUE SVG CHART COMPONENT
function RevenueSVGChart({ points }: { points: Array<{ date: string; revenue: number; mrr: number }> }) {
  if (!points || points.length === 0) return (
    <div style={{ padding: "40px", textAlign: "center", color: "#64748B" }}>
      No revenue chart data points available for this period.
    </div>
  );
  const width = 600;
  const height = 180;
  const maxVal = Math.max(...points.map((p) => Math.max(p.revenue, p.mrr, 10)), 35);
  const minVal = 0;

  const getX = (idx: number) => Math.round((idx / Math.max(1, points.length - 1)) * width);
  const getY = (val: number) => Math.round(height - 20 - ((val - minVal) / (maxVal - minVal)) * (height - 40));

  const coords = points.map((p, i) => ({ x: getX(i), y: getY(p.revenue), ...p }));
  const pathD = coords.reduce((acc, pt, idx) => (idx === 0 ? `M ${pt.x} ${pt.y}` : `${acc} L ${pt.x} ${pt.y}`), "");
  const fillD = `${pathD} L ${width} ${height - 20} L 0 ${height - 20} Z`;

  return (
    <div className="chart-box" style={{ position: "relative" }}>
      <svg viewBox={`0 0 ${width} ${height + 25}`} preserveAspectRatio="none">
        <defs>
          <linearGradient id="indigo-gradient-dyn" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#4F46E5" stopOpacity="0.3" />
            <stop offset="100%" stopColor="#4F46E5" stopOpacity="0.0" />
          </linearGradient>
        </defs>

        <line x1="0" y1="40" x2="600" y2="40" stroke="#F1F5F9" strokeWidth="1" />
        <line x1="0" y1="90" x2="600" y2="90" stroke="#F1F5F9" strokeWidth="1" />
        <line x1="0" y1="140" x2="600" y2="140" stroke="#F1F5F9" strokeWidth="1" />

        <path d={fillD} fill="url(#indigo-gradient-dyn)" />
        <path d={pathD} fill="none" stroke="#4F46E5" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />

        {coords.map((pt, idx) => (
          <g key={idx}>
            <circle cx={pt.x} cy={pt.y} r="4" fill="#4F46E5" stroke="#FFFFFF" strokeWidth="2">
              <title>{`${pt.date}: $${pt.revenue.toFixed(2)} MRR`}</title>
            </circle>
            {(idx === 0 || idx === Math.floor(points.length / 2) || idx === points.length - 1) && (
              <text x={pt.x} y={height + 15} textAnchor="middle" fill="#94A3B8" fontSize="11" fontWeight="500">
                {pt.date}
              </text>
            )}
          </g>
        ))}
      </svg>
    </div>
  );
}

function PaginationBar({
  page,
  totalPages,
  totalCount,
  onPageChange,
}: {
  page: number;
  totalPages: number;
  totalCount: number;
  onPageChange: (newPage: number) => void;
}) {
  if (totalPages <= 1) return null;

  const pageNumbers: number[] = [];
  const startPage = Math.max(1, page - 2);
  const endPage = Math.min(totalPages, startPage + 4);
  for (let i = startPage; i <= endPage; i++) {
    pageNumbers.push(i);
  }

  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", borderTop: "1px solid var(--border-light)", background: "var(--bg-surface)", flexWrap: "wrap", gap: "10px" }}>
      <span style={{ fontSize: "12px", color: "var(--text-secondary)" }}>
        Page <strong>{page}</strong> of <strong>{totalPages}</strong> ({totalCount} items)
      </span>
      <div style={{ display: "flex", gap: "6px", alignItems: "center" }}>
        <button
          type="button"
          disabled={page <= 1}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onPageChange(page - 1);
          }}
          className="btn-secondary"
          style={{ padding: "4px 10px", fontSize: "12px", opacity: page <= 1 ? 0.5 : 1, cursor: page <= 1 ? "not-allowed" : "pointer", display: "inline-flex", alignItems: "center", gap: "4px" }}
        >
          <FAIcon name="arrow-left" size="xs" /> Previous
        </button>
        {pageNumbers.map((p) => (
          <button
            key={p}
            type="button"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onPageChange(p);
            }}
            className={p === page ? "btn-primary" : "btn-secondary"}
            style={{ padding: "4px 9px", fontSize: "12px", fontWeight: p === page ? 700 : 500, cursor: "pointer" }}
          >
            {p}
          </button>
        ))}
        <button
          type="button"
          disabled={page >= totalPages}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onPageChange(page + 1);
          }}
          className="btn-secondary"
          style={{ padding: "4px 10px", fontSize: "12px", opacity: page >= totalPages ? 0.5 : 1, cursor: page >= totalPages ? "not-allowed" : "pointer", display: "inline-flex", alignItems: "center", gap: "4px" }}
        >
          Next <FAIcon name="arrow-right" size="xs" />
        </button>
      </div>
    </div>
  );
}

export default function SaaSAdminDashboardRoute() {
  // 1. ALL REACT HOOKS AT TOP LEVEL OF COMPONENT (STRICT ADHERENCE TO REACT RULES OF HOOKS)
  const loaderData = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const navigation = useNavigation();
  const openaiTestFetcher = useFetcher();
  const geminiTestFetcher = useFetcher();

  const isSubmitting = navigation.state === "submitting" || navigation.state === "loading";

  // Login State
  const [loginPassword, setLoginPassword] = useState("");
  const [loginError, setLoginError] = useState("");

  // Mobile Navigation Sidebar Drawer State
  const [isMobileOpen, setIsMobileOpen] = useState(false);

  // Action Modals & Drawers State
  const [showAddStoreModal, setShowAddStoreModal] = useState(false);
  const [editingStore, setEditingStore] = useState<any | null>(null);
  const [managingSubStore, setManagingSubStore] = useState<any | null>(null);
  const [viewingStoreDetails, setViewingStoreDetails] = useState<any | null>(null);
  const [showNotificationsDrawer, setShowNotificationsDrawer] = useState(false);
  const [showHelpModal, setShowHelpModal] = useState(false);
  const [selectedNotification, setSelectedNotification] = useState<any | null>(null);
  const [showAddPlanModal, setShowAddPlanModal] = useState(false);
  const [editingPlan, setEditingPlan] = useState<any | null>(null);
  const [deletingPlan, setDeletingPlan] = useState<any | null>(null);
  const [showAddHelplineModal, setShowAddHelplineModal] = useState(false);
  const [editingHelpline, setEditingHelpline] = useState<any | null>(null);
  const [deletingHelpline, setDeletingHelpline] = useState<any | null>(null);

  // Notifications Popover & Read State
  const notificationFetcher = useFetcher();
  const [notificationsList, setNotificationsList] = useState<any[]>(loaderData?.notificationsList || []);
  const [unreadCount, setUnreadCount] = useState<number>(loaderData?.unreadNotificationCount ?? 0);
  const [isMarkingAllRead, setIsMarkingAllRead] = useState(false);
  const [loadingNotificationId, setLoadingNotificationId] = useState<string | null>(null);
  const notificationsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (loaderData) {
      if (loaderData.notificationsList) {
        setNotificationsList(loaderData.notificationsList);
      }
      if (typeof loaderData.unreadNotificationCount === "number") {
        setUnreadCount(loaderData.unreadNotificationCount);
      }
      if (typeof loaderData.search === "string") {
        setSearchQuery(loaderData.search);
      }
      if (typeof loaderData.statusFilter === "string") {
        setStatusFilter(loaderData.statusFilter);
      }
      if (typeof loaderData.typeFilter === "string") {
        setTypeFilter(loaderData.typeFilter);
      }
    }
  }, [
    loaderData?.notificationsList,
    loaderData?.unreadNotificationCount,
    loaderData?.search,
    loaderData?.statusFilter,
    loaderData?.typeFilter,
  ]);

  useEffect(() => {
    if (notificationFetcher.data) {
      const res = notificationFetcher.data as any;
      if (res.success) {
        if (typeof res.unreadCount === "number") {
          setUnreadCount(res.unreadCount);
        }
        if (res.intent === "mark_all_notifications_read") {
          setNotificationsList((prev) =>
            prev.map((item) => ({ ...item, isRead: true, status: "READ" }))
          );
          setToastMessage({ type: "success", text: "All notifications marked as read." });
        }
      } else if (res.error || res.message) {
        setToastMessage({ type: "error", text: res.error || res.message });
      }
      setIsMarkingAllRead(false);
      setLoadingNotificationId(null);
    }
  }, [notificationFetcher.data]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (notificationsRef.current && !notificationsRef.current.contains(event.target as Node)) {
        setShowNotificationsDrawer(false);
      }
    }
    if (showNotificationsDrawer) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [showNotificationsDrawer]);

  const handleToggleNotifications = (e?: React.MouseEvent) => {
    if (e) e.stopPropagation();
    setShowNotificationsDrawer((prev) => !prev);
  };

  const handleMarkAllRead = () => {
    if (unreadCount === 0 || isMarkingAllRead) return;
    setIsMarkingAllRead(true);

    // Optimistic UI update
    setNotificationsList((prev) =>
      prev.map((item) => ({ ...item, isRead: true, status: "READ" }))
    );
    setUnreadCount(0);

    notificationFetcher.submit(
      { _intent: "mark_all_notifications_read" },
      { method: "post" }
    );
  };

  const handleNotificationClick = (n: any) => {
    setLoadingNotificationId(n.id);
    const updatedNotification = { ...n, isRead: true, status: "READ" };
    setSelectedNotification(updatedNotification);

    if (!n.isRead) {
      // Optimistic update for single notification
      setNotificationsList((prev) =>
        prev.map((item) => (item.id === n.id ? updatedNotification : item))
      );
      setUnreadCount((prev) => Math.max(0, prev - 1));

      notificationFetcher.submit(
        { _intent: "mark_notification_read", id: n.id },
        { method: "post" }
      );
    } else {
      setLoadingNotificationId(null);
    }
  };

  // Filter & Search State
  const [searchQuery, setSearchQuery] = useState(loaderData?.search || "");
  const [planFilter, setPlanFilter] = useState(loaderData?.planFilter || "ALL");
  const [statusFilter, setStatusFilter] = useState(loaderData?.statusFilter || "ALL");
  const [typeFilter, setTypeFilter] = useState(loaderData?.typeFilter || "ALL");
  const [eventTypeFilter, setEventTypeFilter] = useState(loaderData?.eventTypeFilter || "ALL");
  const [sortBy, setSortBy] = useState(loaderData?.sortBy || "date");
  const [sortDir, setSortDir] = useState(loaderData?.sortDir || "desc");
  const [selectedTimeframe, setSelectedTimeframe] = useState(loaderData?.timeframe || "30d");
  const [pageSize, setPageSize] = useState(loaderData?.pageSize || 10);
  const [selectedTxModal, setSelectedTxModal] = useState<any | null>(null);
  const [adjustStoreItem, setAdjustStoreItem] = useState<any | null>(null);

  const updateUrlFilter = (updates: Record<string, string | number>) => {
    setSearchParams((prevParams) => {
      const newParams = new URLSearchParams(prevParams);
      Object.entries(updates).forEach(([key, value]) => {
        if (value === "" || value === "ALL" || value === null || value === undefined) {
          newParams.delete(key);
        } else {
          newParams.set(key, String(value));
        }
      });
      if (!("page" in updates)) {
        newParams.set("page", "1");
      }
      return newParams;
    });
  };

  // Toast Notification State
  const [toastMessage, setToastMessage] = useState<{ type: "success" | "error" | "info"; text: string } | null>(null);

  // System Integrations State
  const integrations = loaderData?.integrationSettings;
  const isUnmasked = loaderData?.unmask || false;

  const [activeAIProvider, setActiveAIProvider] = useState(integrations?.aiProvider || "openai");
  const [openaiApiKey, setOpenaiApiKey] = useState(integrations?.openaiApiKeyMasked || "");
  const [openaiModel, setOpenaiModel] = useState(integrations?.openaiModel || "gpt-4o-mini");
  const [openaiTemperature, setOpenaiTemperature] = useState(integrations?.openaiTemperature ?? 0.7);
  const [openaiMaxTokens, setOpenaiMaxTokens] = useState(integrations?.openaiMaxTokens ?? 1000);
  const [openaiEnabled, setOpenaiEnabled] = useState(integrations?.openaiEnabled ?? true);

  const [geminiApiKey, setGeminiApiKey] = useState(integrations?.geminiApiKeyMasked || "");
  const [geminiModel, setGeminiModel] = useState(integrations?.geminiModel || "gemini-3.6-flash");
  const [geminiTemperature, setGeminiTemperature] = useState(integrations?.geminiTemperature ?? 0.7);
  const [geminiMaxTokens, setGeminiMaxTokens] = useState(integrations?.geminiMaxTokens ?? 1000);
  const [geminiEnabled, setGeminiEnabled] = useState(integrations?.geminiEnabled ?? true);

  const [openaiTestResult, setOpenaiTestResult] = useState<{ success?: boolean; message?: string } | null>(null);
  const [geminiTestResult, setGeminiTestResult] = useState<{ success?: boolean; message?: string } | null>(null);

  useEffect(() => {
    if (integrations) {
      setActiveAIProvider(integrations.aiProvider || "openai");
      setOpenaiApiKey(integrations.openaiApiKeyMasked || "");
      setOpenaiModel(integrations.openaiModel || "gpt-4o-mini");
      setOpenaiTemperature(integrations.openaiTemperature ?? 0.7);
      setOpenaiMaxTokens(integrations.openaiMaxTokens ?? 1000);
      setOpenaiEnabled(integrations.openaiEnabled ?? true);

      setGeminiApiKey(integrations.geminiApiKeyMasked || "");
      setGeminiModel(integrations.geminiModel || "gemini-3.6-flash");
      setGeminiTemperature(integrations.geminiTemperature ?? 0.7);
      setGeminiMaxTokens(integrations.geminiMaxTokens ?? 1000);
      setGeminiEnabled(integrations.geminiEnabled ?? true);
    }
  }, [integrations]);

  useEffect(() => {
    if (openaiTestFetcher.data && (openaiTestFetcher.data as any).testResult) {
      const res = (openaiTestFetcher.data as any).testResult;
      setOpenaiTestResult({ success: res.success, message: res.message });
      setToastMessage({
        type: res.success ? "success" : "error",
        text: res.message,
      });
    }
  }, [openaiTestFetcher.data]);

  useEffect(() => {
    if (geminiTestFetcher.data && (geminiTestFetcher.data as any).testResult) {
      const res = (geminiTestFetcher.data as any).testResult;
      setGeminiTestResult({ success: res.success, message: res.message });
      setToastMessage({
        type: res.success ? "success" : "error",
        text: res.message,
      });
    }
  }, [geminiTestFetcher.data]);

  // URL Query Param Driven Modals (Failsafe & Survival over page refresh/SPA routing)
  const modalParam = searchParams.get("modal");
  const editShopIdParam = searchParams.get("editShopId");

  const activeAddStoreModal = showAddStoreModal || modalParam === "add_store";
  const storesList = loaderData?.adminStoresData?.stores || [];

  const activeEditStore = editingStore || (
    modalParam === "edit_store" && editShopIdParam
      ? storesList.find((st: any) => st.id === editShopIdParam)
      : null
  );

  const activePlanStore = managingSubStore || (
    modalParam === "manage_plan" && editShopIdParam
      ? storesList.find((st: any) => st.id === editShopIdParam)
      : null
  );

  const activeStoreDetails = viewingStoreDetails || (
    modalParam === "store_details" && editShopIdParam
      ? storesList.find((st: any) => st.id === editShopIdParam)
      : null
  );

  const activeView = loaderData?.view || "dashboard";

  const handleCloseAddModal = () => {
    setShowAddStoreModal(false);
    navigate(`/saas-admin?view=${activeView}`);
  };

  const handleCloseEditModal = () => {
    setEditingStore(null);
    navigate(`/saas-admin?view=${activeView}`);
  };

  const handleClosePlanModal = () => {
    setManagingSubStore(null);
    navigate(`/saas-admin?view=${activeView}`);
  };

  const handleCloseDetailsModal = () => {
    setViewingStoreDetails(null);
    navigate(`/saas-admin?view=${activeView}`);
  };

  useEffect(() => {
    if (actionData) {
      if (actionData.message) {
        setToastMessage({
          type: actionData.success !== false ? "success" : "error",
          text: actionData.message,
        });
      }
      if (actionData.success) {
        if (actionData.intent === "create_store") handleCloseAddModal();
        if (actionData.intent === "edit_store") handleCloseEditModal();
        if (actionData.intent === "update_subscription") handleClosePlanModal();
      }
      if (actionData.testResult) {
        setToastMessage({
          type: actionData.testResult.success ? "success" : "error",
          text: actionData.testResult.message,
        });
        if (actionData.testResult.provider === "openai") {
          setOpenaiTestResult({ success: actionData.testResult.success, message: actionData.testResult.message });
        } else if (actionData.testResult.provider === "gemini") {
          setGeminiTestResult({ success: actionData.testResult.success, message: actionData.testResult.message });
        }
      }
    }
  }, [actionData]);

  const handleToggleUnmaskPII = () => {
    const newUnmask = !isUnmasked;
    const currentUrl = new URL(window.location.href);
    if (newUnmask) {
      currentUrl.searchParams.set("unmask", "true");
    } else {
      currentUrl.searchParams.delete("unmask");
    }
    navigate(`${currentUrl.pathname}${currentUrl.search}`);
  };

  const handleTimeframeChange = (tf: string) => {
    setSelectedTimeframe(tf);
    const currentUrl = new URL(window.location.href);
    currentUrl.searchParams.set("view", "revenue");
    currentUrl.searchParams.set("timeframe", tf);
    navigate(`${currentUrl.pathname}${currentUrl.search}`);
  };  // 2. UNAUTHENTICATED RENDER
  if (!loaderData?.isAuthenticated) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "var(--bg-app)", padding: "20px" }}>
        <div style={{ backgroundColor: "var(--bg-surface)", borderRadius: "var(--radius-modal)", width: "100%", maxWidth: "420px", padding: "36px", boxShadow: "var(--shadow-modal)", display: "flex", flexDirection: "column", gap: "24px", margin: "0 auto", border: "1px solid var(--border-default)" }}>
          <div style={{ textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: "12px" }}>
            <div style={{ width: "40px", height: "40px", borderRadius: "10px", backgroundColor: "var(--brand-primary)", color: "var(--text-inverse)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: "16px" }}>
              SP
            </div>
            <div>
              <h2 className="page-title" style={{ textAlign: "center" }}>ShopPilot AI SaaS Admin</h2>
              <p className="page-description" style={{ marginTop: "4px" }}>Cryptographically secured HMAC session portal.</p>
            </div>
          </div>

          <Form method="post" reloadDocument style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
            <input type="hidden" name="_intent" value="admin_login" />
            <div>
              <label className="input-label">Admin Security Key</label>
              <input
                type="password"
                name="password"
                autoComplete="current-password"
                placeholder="Enter secret key..."
                value={loginPassword}
                onChange={(e) => setLoginPassword(e.target.value)}
                className="input-field"
                style={{ width: "100%" }}
                required
              />
            </div>

            {(actionData?.success === false && actionData?.message ? actionData.message : loginError) && (
              <div style={{ padding: "10px 12px", borderRadius: "var(--radius-input)", backgroundColor: "var(--color-error-bg)", color: "var(--color-error-text)", fontSize: "12px", fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                <FAIcon name="triangle-exclamation" />
                <span>{actionData?.success === false && actionData?.message ? actionData.message : loginError}</span>
              </div>
            )}

            <button
              type="submit"
              disabled={isSubmitting}
              className="btn-primary"
              style={{ width: "100%", height: "40px", fontSize: "14px", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px" }}
            >
              <span>{isSubmitting ? "Authenticating..." : "Unlock Admin Dashboard"}</span>
              {!isSubmitting && <FAIcon name="arrow-right" size="xs" />}
            </button>
          </Form>
        </div>
      </div>
    );
  }

  // 3. AUTHENTICATED DASHBOARD RENDER
  return (
    <div className="saas-container">
      {toastMessage && (
        <div className={`toast-banner ${toastMessage.type === "success" ? "toast-success" : "toast-error"}`}>
          <FAIcon name={toastMessage.type === "success" ? "circle-check" : "triangle-exclamation"} />
          <span style={{ flex: 1 }}>{toastMessage.text}</span>
          <button type="button" style={{ background: "none", border: "none", cursor: "pointer", fontWeight: 700 }} onClick={() => setToastMessage(null)}>
            <FAIcon name="xmark" />
          </button>
        </div>
      )}

      {isMobileOpen && <div className="modal-overlay" style={{ zIndex: 45 }} onClick={() => setIsMobileOpen(false)} />}

      <aside className={`sidebar ${isMobileOpen ? "mobile-open" : ""}`}>
        <div className="sidebar-brand">
          <div className="brand-icon">
            <FAIcon name="robot" />
          </div>
          <div>
            <div className="brand-title">SHOPPILOT AI</div>
            <div className="brand-subtitle">SAAS ADMIN</div>
          </div>
        </div>

        <nav className="sidebar-menu">
          <div className="nav-section">
            <div className="nav-section-title">Overview</div>
            <Link to="/saas-admin?view=dashboard" className={`nav-item ${activeView === "dashboard" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="house" className="nav-icon" /> <span>Dashboard</span>
            </Link>
            <Link to="/saas-admin?view=analytics" className={`nav-item ${activeView === "analytics" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="chart-line" className="nav-icon" /> <span>Session Analytics</span>
            </Link>
          </div>

          <div className="nav-section">
            <div className="nav-section-title">Commerce</div>
            <Link to="/saas-admin?view=stores" className={`nav-item ${activeView === "stores" || activeView === "store_details" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="store" className="nav-icon" /> <span>Stores ({loaderData?.adminKPIs?.totalStores || 0})</span>
            </Link>
            <Link to="/saas-admin?view=subscriptions" className={`nav-item ${activeView === "subscriptions" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="shield-halved" className="nav-icon" /> <span>Subscriptions</span>
            </Link>
            <Link to="/saas-admin?view=plans" className={`nav-item ${activeView === "plans" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="tags" className="nav-icon" /> <span>Plans & Pricing ({loaderData?.adminPlans?.length || 0})</span>
            </Link>
            <Link to="/saas-admin?view=helplines" className={`nav-item ${activeView === "helplines" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="headset" className="nav-icon" /> <span>Helplines & Support ({loaderData?.adminHelplines?.length || 0})</span>
            </Link>
          </div>

          <div className="nav-section">
            <div className="nav-section-title">Finance</div>
            <Link to="/saas-admin?view=revenue" className={`nav-item ${activeView === "revenue" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="dollar-sign" className="nav-icon" /> <span>Revenue</span>
            </Link>
            <Link to="/saas-admin?view=transactions" className={`nav-item ${activeView === "transactions" || activeView === "transaction_details" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="receipt" className="nav-icon" /> <span>Transactions</span>
            </Link>
          </div>

          <div className="nav-section">
            <div className="nav-section-title">System</div>
            <Link to="/saas-admin?view=notifications" className={`nav-item ${activeView === "notifications" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="bell" className="nav-icon" /> <span>Notifications</span>
              {activeView !== "notifications" && unreadCount > 0 && (
                <span className="status-badge error" style={{ marginLeft: "auto", fontSize: "10px", padding: "1px 6px" }}>
                  {unreadCount}
                </span>
              )}
            </Link>
            <Link to="/saas-admin?view=integrations" className={`nav-item ${activeView === "integrations" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="plug" className="nav-icon" /> <span>Integrations</span>
            </Link>
            <Link to="/saas-admin?view=settings" className={`nav-item ${activeView === "settings" ? "active" : ""}`} onClick={() => setIsMobileOpen(false)}>
              <FAIcon name="gear" className="nav-icon" /> <span>Settings</span>
            </Link>
          </div>
        </nav>

        <div className="sidebar-footer">
          <div className="avatar">AD</div>
          <div className="user-info">
            <div className="user-name">SaaS Operator</div>
            <div className="user-role">HMAC Session Active</div>
          </div>
          <Form method="post" reloadDocument>
            <input type="hidden" name="_intent" value="admin_logout" />
            <button type="submit" className="icon-btn" title="Sign Out" style={{ width: "28px", height: "28px" }}>
              <FAIcon name="arrow-right-from-bracket" size="sm" />
            </button>
          </Form>
        </div>
      </aside>

      <div className="main-wrapper">
        <header className="top-header">
          <div className="header-left">
            <button type="button" className="mobile-hamburger" onClick={() => setIsMobileOpen(!isMobileOpen)}>☰</button>
            <div>
              <h1 className="page-title">
                {activeView === "analytics"
                  ? "Session & Catalog Analytics"
                  : activeView === "revenue"
                  ? "Financial Revenue & MRR"
                  : activeView === "subscriptions"
                  ? "Subscriptions Analytics"
                  : activeView === "plans"
                  ? "Subscription Plans & Pricing"
                  : activeView === "helplines"
                  ? "Helplines & Support Management"
                  : activeView === "transactions"
                  ? "Transactions Log"
                  : activeView === "stores"
                  ? "Stores Management"
                  : activeView === "integrations"
                  ? "System Integrations"
                  : activeView === "settings"
                  ? "Global SaaS Settings"
                  : "Dashboard Overview"}
              </h1>
            </div>
          </div>

          <div className="header-actions">
            {loaderData?.platformSettings?.defaultStoreDomain && (
              <div style={{ display: "flex", alignItems: "center", gap: "8px", flexWrap: "wrap" }}>
                <a
                  href={`https://${loaderData.platformSettings.defaultStoreDomain}`}
                  target="_blank"
                  rel="noreferrer"
                  className="btn-secondary"
                  style={{
                    padding: "4px 10px",
                    fontSize: "12px",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: "6px",
                    textDecoration: "none",
                    borderRadius: "6px",
                    background: "#f0fdf4",
                    border: "1px solid #bbf7d0",
                    color: "#166534",
                    fontWeight: 600,
                  }}
                  title="Open Primary Storefront"
                >
                  <FAIcon name="store" size="sm" />
                  <span>{loaderData.platformSettings.defaultStoreDomain}</span>
                  <FAIcon name="arrow-up-right-from-square" size="xs" />
                </a>

                {loaderData?.platformSettings?.partnerDashboardUrl && (
                  <a
                    href={loaderData.platformSettings.partnerDashboardUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="btn-secondary"
                    style={{
                      padding: "4px 10px",
                      fontSize: "12px",
                      display: "inline-flex",
                      alignItems: "center",
                      gap: "6px",
                      textDecoration: "none",
                      borderRadius: "6px",
                      background: "#eff6ff",
                      border: "1px solid #bfdbfe",
                      color: "#1e40af",
                      fontWeight: 600,
                    }}
                    title="Open Shopify Partner Dashboard"
                  >
                    <FAIcon name="briefcase" size="sm" />
                    <span>Partner Dashboard</span>
                    <FAIcon name="arrow-up-right-from-square" size="xs" />
                  </a>
                )}
              </div>
            )}

            <Link
              to="/saas-admin?view=notifications"
              className="icon-btn"
              title="System Notifications"
              style={{ textDecoration: "none", position: "relative" }}
            >
              <FAIcon name="bell" />
              {activeView !== "notifications" && unreadCount > 0 && (
                <span
                  style={{
                    position: "absolute",
                    top: "-4px",
                    right: "-4px",
                    backgroundColor: "var(--color-error)",
                    color: "var(--text-inverse)",
                    fontSize: "10px",
                    fontWeight: 700,
                    borderRadius: "var(--radius-pill)",
                    width: "16px",
                    height: "16px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  {unreadCount}
                </span>
              )}
            </Link>
          </div>
        </header>

        <main className="content-body">
          {/* VIEW 1: NOTIFICATIONS CENTER */}
          {activeView === "notifications" ? (
            <div className="card">
              <div className="card-header">
                <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
                  <FAIcon name="bell" style={{ fontSize: "18px", color: "var(--brand-primary)" }} />
                  <div>
                    <h3 className="card-heading">System Notifications Center ({unreadCount})</h3>
                    <p className="page-description">Real-time database system notifications, shop sync events, and AI alerts.</p>
                  </div>
                </div>
                <div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
                  <button
                    type="button"
                    className="btn-secondary"
                    disabled={unreadCount === 0 || isMarkingAllRead}
                    onClick={handleMarkAllRead}
                    style={{ opacity: unreadCount === 0 ? 0.6 : 1, cursor: unreadCount === 0 ? "not-allowed" : "pointer" }}
                  >
                    {isMarkingAllRead ? "Marking as read..." : `Mark All as Read (${unreadCount})`}
                  </button>
                </div>
              </div>

              <div className="toolbar">
                <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap", flex: 1 }}>
                  <input
                    type="text"
                    placeholder="Search notifications..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        updateUrlFilter({ search: searchQuery.trim(), statusFilter, typeFilter, view: "notifications", page: 1 });
                      }
                    }}
                    className="input-field"
                    style={{ minWidth: "220px" }}
                  />
                  <select
                    className="select-input"
                    value={statusFilter}
                    onChange={(e) => {
                      const val = e.target.value;
                      setStatusFilter(val);
                      updateUrlFilter({ statusFilter: val, typeFilter, search: searchQuery.trim(), view: "notifications", page: 1 });
                    }}
                  >
                    <option value="ALL">All Statuses</option>
                    <option value="UNREAD">UNREAD</option>
                    <option value="READ">READ</option>
                  </select>
                  <select
                    className="select-input"
                    value={typeFilter}
                    onChange={(e) => {
                      const val = e.target.value;
                      setTypeFilter(val);
                      updateUrlFilter({ typeFilter: val, statusFilter, search: searchQuery.trim(), view: "notifications", page: 1 });
                    }}
                  >
                    <option value="ALL">All Notification Types</option>
                    <option value="SHOPIFY_SYNC_SUCCESS">Shopify Catalog Synced</option>
                    <option value="SHOPIFY_CONNECTED">Shopify Connected</option>
                    <option value="AI_CONFIG_UPDATED">AI Configuration Updated</option>
                    <option value="SUBSCRIPTION_UPDATED">Subscription Plan Updated</option>
                    <option value="USAGE_LIMIT_WARNING">Usage Limit Warning</option>
                    <option value="SYSTEM_ALERT">System Alert</option>
                  </select>
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={() => updateUrlFilter({ search: searchQuery.trim(), statusFilter, typeFilter, view: "notifications", page: 1 })}
                  >
                    Filter
                  </button>
                  {(searchQuery || statusFilter !== "ALL" || typeFilter !== "ALL") && (
                    <button
                      type="button"
                      className="btn-secondary"
                      onClick={() => {
                        setSearchQuery("");
                        setStatusFilter("ALL");
                        setTypeFilter("ALL");
                        updateUrlFilter({ search: "", statusFilter: "ALL", typeFilter: "ALL", view: "notifications", page: 1 });
                      }}
                    >
                      Reset
                    </button>
                  )}
                </div>
              </div>

              <div className="table-responsive">
                <table className="modern-table">
                  <thead>
                    <tr>
                      <th>Event / Title</th>
                      <th>Details & Scope</th>
                      <th>Created Date</th>
                      <th>Updated Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {notificationsList.length === 0 ? (
                      <tr>
                        <td colSpan={4} style={{ textAlign: "center", padding: "40px 20px", color: "var(--text-secondary)" }}>
                          <FAIcon name={(searchQuery || statusFilter !== "ALL" || typeFilter !== "ALL") ? "magnifying-glass" : "bell-slash"} style={{ fontSize: "26px", color: "var(--text-muted)", marginBottom: "8px" }} />
                          <div style={{ fontWeight: 700, color: "var(--text-primary)", fontSize: "15px" }}>
                            {(searchQuery || statusFilter !== "ALL" || typeFilter !== "ALL") ? "No matching notifications" : "No notifications"}
                          </div>
                          <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "4px" }}>
                            {(searchQuery || statusFilter !== "ALL" || typeFilter !== "ALL") ? "Try changing your search or filters." : "You're all caught up."}
                          </div>
                          {(searchQuery || statusFilter !== "ALL" || typeFilter !== "ALL") && (
                            <button
                              type="button"
                              className="btn-secondary"
                              style={{ marginTop: "12px" }}
                              onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setTypeFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", typeFilter: "ALL", view: "notifications" }); }}
                            >
                              Clear filters
                            </button>
                          )}
                        </td>
                      </tr>
                    ) : (
                      notificationsList.map((n: any) => {
                        const isRead = n.isRead;
                        return (
                          <tr key={n.id} className={isRead ? "" : "unread-row"} style={{ cursor: "pointer" }} onClick={() => handleNotificationClick(n)}>
                            <td>
                              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                {!isRead && (
                                  <span style={{ width: "6px", height: "6px", borderRadius: "50%", backgroundColor: "var(--brand-primary)", display: "inline-block", flexShrink: 0 }} />
                                )}
                                <span style={{ color: n.type === "success" ? "var(--color-success)" : n.type === "warning" ? "var(--color-warning)" : n.type === "error" ? "var(--color-error)" : "var(--color-info)", flexShrink: 0 }}>
                                  <FAIcon name={n.type === "success" ? "circle-check" : n.type === "warning" ? "triangle-exclamation" : n.type === "error" ? "circle-xmark" : "circle-info"} />
                                </span>
                                <strong style={{ fontSize: "14px", fontWeight: isRead ? 500 : 600, color: isRead ? "var(--text-primary)" : "#111827" }}>{n.action}</strong>
                              </div>
                            </td>
                            <td style={{ fontSize: "13px", color: isRead ? "var(--text-secondary)" : "#374151" }}>{n.details}</td>
                            <td className="notification-time">{n.createdAt}</td>
                            <td className="notification-time">{n.updatedAt || n.createdAt}</td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>

              <PaginationBar
                page={loaderData?.notificationsPage || 1}
                totalPages={loaderData?.totalNotificationsPages || 1}
                totalCount={loaderData?.totalNotificationsCount || 0}
                onPageChange={(newPage) => updateUrlFilter({ page: newPage, view: "notifications" })}
              />
            </div>
          ) : activeView === "integrations" ? (
            /* VIEW 2: INTEGRATIONS */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="card" style={{ background: "linear-gradient(135deg, #EEF2FF 0%, #E0E7FF 100%)", borderColor: "var(--brand-border)", padding: "18px 24px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
                  <div style={{ width: "40px", height: "40px", borderRadius: "10px", backgroundColor: "var(--brand-primary)", color: "var(--text-inverse)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "18px" }}>
                    <FAIcon name="shield-halved" />
                  </div>
                  <div>
                    <h4 className="section-heading" style={{ fontSize: "15px", color: "#1E1B4B" }}>Enterprise API Key Security & AES-256-GCM Encryption</h4>
                    <p className="page-description" style={{ color: "#3730A3", marginTop: "2px" }}>
                      API keys are stored encrypted at rest using AES-256-GCM. Plaintext credentials are never exposed in browser requests or log files.
                    </p>
                  </div>
                </div>
              </div>

              {/* GLOBAL PROVIDER SELECTOR */}
              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <FAIcon name="gear" /> Global AI Engine Provider Selection
                  </h3>
                </div>

                <Form method="post" style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                  <input type="hidden" name="shopId" value={loaderData?.targetShopId || "global"} />
                  <input type="hidden" name="_intent" value="save_global_provider" />

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
                    <label style={{ display: "flex", gap: "12px", padding: "16px", borderRadius: "var(--radius-card)", border: activeAIProvider === "openai" ? "2px solid var(--brand-primary)" : "1px solid var(--border-default)", backgroundColor: activeAIProvider === "openai" ? "var(--brand-light)" : "var(--bg-surface)", cursor: "pointer" }}>
                      <input type="radio" name="aiProvider" value="openai" checked={activeAIProvider === "openai"} onChange={(e) => setActiveAIProvider(e.target.value)} style={{ accentColor: "var(--brand-primary)" }} />
                      <div>
                        <strong className="val-important" style={{ fontSize: "14px" }}>OpenAI API (GPT Engines)</strong>
                        <p className="page-description" style={{ marginTop: "4px" }}>Industry standard GPT-4o & GPT-4o Mini models.</p>
                      </div>
                    </label>

                    <label style={{ display: "flex", gap: "12px", padding: "16px", borderRadius: "var(--radius-card)", border: activeAIProvider === "gemini" ? "2px solid var(--brand-primary)" : "1px solid var(--border-default)", backgroundColor: activeAIProvider === "gemini" ? "#F5F3FF" : "var(--bg-surface)", cursor: "pointer" }}>
                      <input type="radio" name="aiProvider" value="gemini" checked={activeAIProvider === "gemini"} onChange={(e) => setActiveAIProvider(e.target.value)} style={{ accentColor: "var(--brand-primary)" }} />
                      <div>
                        <strong className="val-important" style={{ fontSize: "14px" }}>Google Gemini API (Gemini Engines)</strong>
                        <p className="page-description" style={{ marginTop: "4px" }}>Next-gen multimodal Gemini 3.6 Flash & 1.5 Flash models.</p>
                      </div>
                    </label>
                  </div>

                  <div style={{ display: "flex", justifyContent: "flex-end" }}>
                    <button type="submit" disabled={isSubmitting} className="btn-primary">
                      <FAIcon name="floppy-disk" /> Save Provider Selection
                    </button>
                  </div>
                </Form>
              </div>

              {/* OPENAI CARD */}
              <Form method="post" className="card">
                <div className="card-header">
                  <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
                    <div style={{ width: "36px", height: "36px", borderRadius: "var(--radius-input)", backgroundColor: "#10A37F", color: "var(--text-inverse)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>
                      <FAIcon name="robot" />
                    </div>
                    <div>
                      <h3 className="card-heading">OpenAI Configuration</h3>
                      <p className="page-description">Manage OpenAI API key, default model, temperature, and token limits.</p>
                    </div>
                  </div>
                  <span className={`status-badge ${integrations?.openaiHasKey && openaiEnabled ? "success" : "neutral"}`}>
                    {integrations?.openaiHasKey && openaiEnabled ? "✓ Connected" : "Not Configured"}
                  </span>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
                  <div>
                    <label className="input-label">OpenAI API Key</label>
                    <div style={{ display: "flex", gap: "10px" }}>
                      <input
                        type="password"
                        name="openaiApiKey"
                        placeholder="sk-proj-••••••••••••••••"
                        value={openaiApiKey}
                        onChange={(e) => setOpenaiApiKey(e.target.value)}
                        className="input-field"
                        style={{ flex: 1, fontFamily: "monospace" }}
                      />
                      {openaiApiKey && openaiApiKey.startsWith("••••") && (
                        <button type="button" className="btn-secondary" onClick={() => setOpenaiApiKey("")}>
                          Replace Key
                        </button>
                      )}
                    </div>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
                    <div>
                      <label className="input-label">Default Model</label>
                      <select name="openaiModel" className="select-input" style={{ width: "100%" }} value={openaiModel} onChange={(e) => setOpenaiModel(e.target.value)}>
                        <option value="gpt-4o-mini">GPT-4o Mini (Ultra Fast & Recommended)</option>
                        <option value="gpt-4o">GPT-4o (High Performance AI)</option>
                        <option value="gpt-4-turbo">GPT-4 Turbo (Advanced Function Calling)</option>
                        <option value="gpt-3.5-turbo">GPT-3.5 Turbo (Legacy Standard)</option>
                      </select>
                    </div>
                    <div>
                      <label className="input-label">Temperature: {openaiTemperature}</label>
                      <input type="range" name="openaiTemperature" min="0" max="1" step="0.05" value={openaiTemperature} onChange={(e) => setOpenaiTemperature(parseFloat(e.target.value))} style={{ width: "100%", marginTop: "8px", accentColor: "var(--brand-primary)" }} />
                    </div>
                    <div>
                      <label className="input-label">Max Tokens</label>
                      <input type="number" name="openaiMaxTokens" value={openaiMaxTokens} onChange={(e) => setOpenaiMaxTokens(parseInt(e.target.value, 10) || 1000)} className="input-field" style={{ width: "100%" }} />
                    </div>
                  </div>

                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <input type="checkbox" name="openaiEnabled" id="openaiEnabled" value="true" checked={openaiEnabled} onChange={(e) => setOpenaiEnabled(e.target.checked)} style={{ accentColor: "var(--brand-primary)" }} />
                    <label htmlFor="openaiEnabled" className="input-label" style={{ margin: 0, cursor: "pointer" }}>Enable OpenAI Integration</label>
                  </div>

                  {openaiTestResult && (
                    <div style={{ padding: "12px 16px", borderRadius: "var(--radius-input)", fontSize: "13px", fontWeight: 600, backgroundColor: openaiTestResult.success ? "var(--color-success-bg)" : "var(--color-error-bg)", color: openaiTestResult.success ? "var(--color-success-text)" : "var(--color-error-text)", display: "flex", alignItems: "center", gap: "8px" }}>
                      <FAIcon name={openaiTestResult.success ? "circle-check" : "triangle-exclamation"} />
                      <span>{openaiTestResult.message}</span>
                    </div>
                  )}

                  <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "16px", borderTop: "1px solid var(--border-light)" }}>
                    <button
                      type="button"
                      disabled={openaiTestFetcher.state !== "idle" || isSubmitting}
                      className="btn-secondary"
                      onClick={() => {
                        openaiTestFetcher.submit(
                          {
                            _intent: "test_connection_openai",
                            shopId: loaderData?.targetShopId || "global",
                            openaiApiKey,
                            openaiModel,
                          },
                          { method: "post" }
                        );
                      }}
                    >
                      <FAIcon name="circle-check" /> {openaiTestFetcher.state !== "idle" ? "Testing..." : "Test Connection"}
                    </button>
                    <button type="submit" name="_intent" value="save_openai_config" disabled={isSubmitting} className="btn-primary">
                      <FAIcon name="floppy-disk" /> {isSubmitting ? "Saving..." : "Save OpenAI Configuration"}
                    </button>
                  </div>
                </div>
              </Form>

              {/* GOOGLE GEMINI CARD */}
              <Form method="post" className="card">
                <div className="card-header">
                  <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
                    <div style={{ width: "36px", height: "36px", borderRadius: "var(--radius-input)", background: "linear-gradient(135deg, #4285F4 0%, #7C3AED 100%)", color: "var(--text-inverse)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>
                      <FAIcon name="brain" />
                    </div>
                    <div>
                      <h3 className="card-heading">Google Gemini Configuration</h3>
                      <p className="page-description">Manage Google Gemini API credentials, models, and limits.</p>
                    </div>
                  </div>
                  <span className={`status-badge ${integrations?.geminiHasKey && geminiEnabled ? "success" : "neutral"}`}>
                    {integrations?.geminiHasKey && geminiEnabled ? "✓ Connected" : "Not Configured"}
                  </span>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
                  <div>
                    <label className="input-label">Gemini API Key</label>
                    <div style={{ display: "flex", gap: "10px" }}>
                      <input
                        type="password"
                        name="geminiApiKey"
                        placeholder="AIzaSy••••••••••••••••"
                        value={geminiApiKey}
                        onChange={(e) => setGeminiApiKey(e.target.value)}
                        className="input-field"
                        style={{ flex: 1, fontFamily: "monospace" }}
                      />
                      {geminiApiKey && geminiApiKey.startsWith("••••") && (
                        <button type="button" className="btn-secondary" onClick={() => setGeminiApiKey("")}>
                          Replace Key
                        </button>
                      )}
                    </div>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
                    <div>
                      <label className="input-label">Default Model</label>
                      <select name="geminiModel" className="select-input" style={{ width: "100%" }} value={geminiModel} onChange={(e) => setGeminiModel(e.target.value)}>
                        <option value="gemini-1.5-flash">Gemini 1.5 Flash (Next-Gen Fast & Recommended)</option>
                        <option value="gemini-1.5-pro">Gemini 1.5 Pro (Advanced Reasoning & 1M Context)</option>
                        <option value="gemini-2.0-flash">Gemini 2.0 Flash (Experimental)</option>
                      </select>
                    </div>
                    <div>
                      <label className="input-label">Temperature: {geminiTemperature}</label>
                      <input type="range" name="geminiTemperature" min="0" max="1" step="0.05" value={geminiTemperature} onChange={(e) => setGeminiTemperature(parseFloat(e.target.value))} style={{ width: "100%", marginTop: "8px", accentColor: "var(--brand-primary)" }} />
                    </div>
                    <div>
                      <label className="input-label">Max Tokens</label>
                      <input type="number" name="geminiMaxTokens" value={geminiMaxTokens} onChange={(e) => setGeminiMaxTokens(parseInt(e.target.value, 10) || 1000)} className="input-field" style={{ width: "100%" }} />
                    </div>
                  </div>

                  <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <input type="checkbox" name="geminiEnabled" id="geminiEnabled" value="true" checked={geminiEnabled} onChange={(e) => setGeminiEnabled(e.target.checked)} style={{ accentColor: "var(--brand-primary)" }} />
                    <label htmlFor="geminiEnabled" className="input-label" style={{ margin: 0, cursor: "pointer" }}>Enable Google Gemini Integration</label>
                  </div>

                  {geminiTestResult && (
                    <div style={{ padding: "12px 16px", borderRadius: "var(--radius-input)", fontSize: "13px", fontWeight: 600, backgroundColor: geminiTestResult.success ? "var(--color-success-bg)" : "var(--color-error-bg)", color: geminiTestResult.success ? "var(--color-success-text)" : "var(--color-error-text)", display: "flex", alignItems: "center", gap: "8px" }}>
                      <FAIcon name={geminiTestResult.success ? "circle-check" : "triangle-exclamation"} />
                      <span>{geminiTestResult.message}</span>
                    </div>
                  )}

                  <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "16px", borderTop: "1px solid var(--border-light)" }}>
                    <button
                      type="button"
                      disabled={geminiTestFetcher.state !== "idle" || isSubmitting}
                      className="btn-secondary"
                      onClick={() => {
                        geminiTestFetcher.submit(
                          {
                            _intent: "test_connection_gemini",
                            shopId: loaderData?.targetShopId || "global",
                            geminiApiKey,
                            geminiModel,
                          },
                          { method: "post" }
                        );
                      }}
                    >
                      <FAIcon name="circle-check" /> {geminiTestFetcher.state !== "idle" ? "Testing..." : "Test Connection"}
                    </button>
                    <button type="submit" name="_intent" value="save_gemini_config" disabled={isSubmitting} className="btn-primary">
                      <FAIcon name="floppy-disk" /> {isSubmitting ? "Saving..." : "Save Gemini Configuration"}
                    </button>
                  </div>
                </div>
              </Form>
            </div>
          ) : activeView === "stores" ? (
            /* VIEW 3: DEDICATED STORES MANAGEMENT */
            <div className="card">
              <div className="card-header" style={{ justifyContent: "flex-end" }}>
                <div style={{ display: "flex", gap: "10px" }}>
                  <a
                    href={`/saas-admin/export/stores${isUnmasked ? "?unmask=true" : ""}`}
                    className="btn-secondary"
                    download
                  >
                    <FAIcon name="download" /> Export Stores CSV
                  </a>
                  <Link
                    to="/saas-admin?view=stores&modal=add_store"
                    className="btn-primary"
                    onClick={(e) => {
                      e.preventDefault();
                      setShowAddStoreModal(true);
                    }}
                  >
                    <FAIcon name="plus" /> Add Store
                  </Link>
                </div>
              </div>

              <div className="toolbar">
                <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap", flex: 1 }}>
                  <input
                    type="text"
                    placeholder="Search domain or email..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="input-field"
                    style={{ minWidth: "220px" }}
                  />
                  <select
                    className="select-input"
                    value={statusFilter}
                    onChange={(e) => { setStatusFilter(e.target.value); updateUrlFilter({ statusFilter: e.target.value, view: "stores" }); }}
                  >
                    <option value="ALL">All Statuses</option>
                    <option value="ACTIVE">ACTIVE</option>
                    <option value="TRIAL">TRIAL (Free Tier)</option>
                    <option value="UNINSTALLED">UNINSTALLED</option>
                  </select>
                  <select
                    className="select-input"
                    value={planFilter}
                    onChange={(e) => { setPlanFilter(e.target.value); updateUrlFilter({ planFilter: e.target.value, view: "stores" }); }}
                  >
                    <option value="ALL">All Plans</option>
                    {(loaderData?.adminPlans && loaderData.adminPlans.length > 0) ? (
                      loaderData.adminPlans.map((p: any) => (
                        <option key={p.planKey} value={p.planKey}>
                          {p.displayName} ({p.billingInterval === "ONE_TIME" ? (p.price === 0 ? "Free" : `$${p.price} One-time`) : `$${p.price}/mo`})
                        </option>
                      ))
                    ) : (
                      <>
                        <option value="FREE">Free</option>
                        <option value="STARTER">Starter ($29/mo)</option>
                        <option value="PRO">Pro ($79/mo)</option>
                      </>
                    )}
                  </select>
                  <select
                    className="select-input"
                    value={sortBy}
                    onChange={(e) => { setSortBy(e.target.value); updateUrlFilter({ sortBy: e.target.value, view: "stores" }); }}
                  >
                    <option value="newest">Sort: Newest First</option>
                    <option value="oldest">Sort: Oldest First</option>
                    <option value="domain">Sort: Domain (A-Z)</option>
                  </select>
                  <button type="button" className="btn-secondary" onClick={() => updateUrlFilter({ search: searchQuery.trim(), view: "stores" })}>Filter</button>
                  {(searchQuery || statusFilter !== "ALL" || planFilter !== "ALL") && (
                    <button type="button" className="btn-secondary" onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setPlanFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", planFilter: "ALL", view: "stores" }); }}>Reset</button>
                  )}
                </div>
              </div>

              <div className="table-responsive">
                <table className="modern-table">
                  <thead>
                    <tr>
                      <th>Store Domain</th>
                      <th>Status</th>
                      <th>Chatbot Status</th>
                      <th>Plan</th>
                      <th>Conversations</th>
                      <th>AI Usage</th>
                      <th>MRR</th>
                      <th>Last Active</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(loaderData?.adminStoresData?.stores || []).length === 0 ? (
                      <tr>
                        <td colSpan={9} style={{ textAlign: "center", padding: "40px 20px", color: "var(--text-secondary)" }}>
                          <FAIcon name="magnifying-glass" style={{ fontSize: "24px", color: "var(--text-muted)", marginBottom: "8px" }} />
                          <div style={{ fontWeight: 600, color: "var(--text-primary)", fontSize: "14px" }}>No results found</div>
                          <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "4px" }}>Try changing your search or filters.</div>
                          {(searchQuery || statusFilter !== "ALL" || planFilter !== "ALL") && (
                            <button
                              type="button"
                              className="btn-secondary"
                              style={{ marginTop: "12px" }}
                              onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setPlanFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", planFilter: "ALL", view: "stores" }); }}
                            >
                              Clear filters
                            </button>
                          )}
                        </td>
                      </tr>
                    ) : (
                      (loaderData?.adminStoresData?.stores || []).map((s: any) => (
                        <tr key={s.id}>
                          <td>
                            <strong className="val-important" style={{ cursor: "pointer", color: "var(--brand-primary)" }} onClick={() => setViewingStoreDetails(s)}>
                              {s.shopifyDomain}
                            </strong>
                            <div className="page-description" style={{ fontSize: "11px" }}>{s.merchantEmail}</div>
                          </td>
                          <td>
                            <span className={`status-badge ${s.status === "ACTIVE" ? "success" : "error"}`}>
                              {s.status}
                            </span>
                          </td>
                          <td>
                            {s.chatbotAdminDisabled ? (
                              <span
                                className="status-badge error"
                                style={{ display: "inline-flex", alignItems: "center", gap: "4px", fontSize: "11px", fontWeight: 700 }}
                                title="Deactivated by SaaS Admin (Store cannot activate)"
                              >
                                🚫 INACTIVE (ADMIN)
                              </span>
                            ) : s.chatbotEnabled ? (
                              <span
                                className="status-badge success"
                                style={{ display: "inline-flex", alignItems: "center", gap: "4px", fontSize: "11px", fontWeight: 700 }}
                                title="Chatbot is Active on Storefront"
                              >
                                ✓ ACTIVE
                              </span>
                            ) : (
                              <span
                                className="status-badge"
                                style={{ backgroundColor: "#FEF3C7", color: "#92400E", border: "1px solid #FDE68A", display: "inline-flex", alignItems: "center", gap: "4px", fontSize: "11px", fontWeight: 700 }}
                                title="Chatbot is turned off by Merchant"
                              >
                                ⏸ DISABLED (STORE)
                              </span>
                            )}
                          </td>
                          <td>
                            <span className="status-badge neutral">
                              {s.planDisplayName || s.plan}
                            </span>
                          </td>
                          <td><strong className="val-important">{s.conversationCount || 0} chats</strong></td>
                          <td>{s.aiUsageDisplay || (s.plan === "PRO" ? `${s.currentUsage} / 25,000` : "N/A")}</td>
                          <td>
                            <span className="val-important">
                              {s.billingType === "ONE_TIME" ? (s.monthlyPrice === 0 ? "$0.00" : `$${(s.monthlyPrice || 0).toFixed(2)}`) : `$${(s.monthlyPrice || 0).toFixed(2)}`}
                            </span>
                          </td>
                          <td>{s.lastActiveAt}</td>
                          <td>
                            <div style={{ display: "flex", gap: "6px", alignItems: "center" }}>
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ height: "28px", padding: "0 8px", fontSize: "12px" }}
                                onClick={() => setViewingStoreDetails(s)}
                              >
                                Details
                              </button>
                              <Link
                                to={`/saas-admin?view=stores&modal=edit_store&editShopId=${s.id}`}
                                className="btn-secondary"
                                style={{ height: "28px", padding: "0 8px", fontSize: "12px" }}
                                onClick={(e) => {
                                  e.preventDefault();
                                  setEditingStore(s);
                                }}
                              >
                                Edit
                              </Link>
                              <Link
                                to={`/saas-admin?view=stores&modal=manage_plan&editShopId=${s.id}`}
                                className="btn-secondary"
                                style={{ height: "28px", padding: "0 8px", fontSize: "12px" }}
                                onClick={(e) => {
                                  e.preventDefault();
                                  setManagingSubStore(s);
                                }}
                              >
                                Plan
                              </Link>
                              <Form method="post" style={{ margin: 0, display: "inline" }}>
                                <input type="hidden" name="_intent" value="toggle_store_chatbot" />
                                <input type="hidden" name="shopId" value={s.id} />
                                <input type="hidden" name="adminDisabled" value={s.chatbotAdminDisabled ? "false" : "true"} />
                                <button
                                  type="submit"
                                  className="btn-secondary"
                                  style={{
                                    height: "28px",
                                    padding: "0 8px",
                                    fontSize: "11px",
                                    color: s.chatbotAdminDisabled ? "#059669" : "#dc2626",
                                    borderColor: s.chatbotAdminDisabled ? "#a7f3d0" : "#fecaca",
                                    fontWeight: 600,
                                  }}
                                  title={s.chatbotAdminDisabled ? "Reactivate Chatbot (Allow Store to enable)" : "Deactivate Chatbot (Lock & Hide from Store)"}
                                >
                                  {s.chatbotAdminDisabled ? "Enable Bot" : "Disable Bot"}
                                </button>
                              </Form>
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>

              <PaginationBar
                page={loaderData?.adminStoresData?.page || 1}
                totalPages={loaderData?.adminStoresData?.totalPages || 1}
                totalCount={loaderData?.adminStoresData?.totalCount || 0}
                onPageChange={(newPage) => updateUrlFilter({ page: newPage, view: "stores" })}
              />
            </div>
          ) : activeView === "revenue" ? (
            /* VIEW 4: REVENUE & FINANCIAL MRR */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">One-Time Revenue (Free $5 + Boosters)</span>
                  <div className="kpi-number">${(loaderData?.revenueData?.oneTimeRevenue ?? loaderData?.adminKPIs?.oneTimeRevenue ?? 0).toFixed(2)}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Starter MRR ($29/mo)</span>
                  <div className="kpi-number">${(loaderData?.revenueData?.starterMrr ?? loaderData?.adminKPIs?.starterMrr ?? 0).toFixed(2)}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Pro MRR ($79/mo)</span>
                  <div className="kpi-number">${(loaderData?.revenueData?.proMrr ?? loaderData?.adminKPIs?.proMrr ?? 0).toFixed(2)}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Total MRR (Recurring Only)</span>
                  <div className="kpi-number" style={{ color: "var(--brand-primary)" }}>${(loaderData?.revenueData?.mrr || 0).toFixed(2)}</div>
                </div>
              </div>

              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Annual Run Rate (ARR)</span>
                  <div className="kpi-number">${(loaderData?.revenueData?.arr || 0).toFixed(2)}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Growth Rate</span>
                  <div className="kpi-number">{loaderData?.revenueData?.growthRate || 0}%</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">ARPU (Recurring Stores)</span>
                  <div className="kpi-number">${(loaderData?.adminKPIs?.arpu || 0).toFixed(2)}</div>
                </div>
              </div>

              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Revenue Over Time Curve</h3>
                  <div style={{ display: "flex", gap: "10px" }}>
                    <select className="select-input" value={selectedTimeframe} onChange={(e) => handleTimeframeChange(e.target.value)}>
                      <option value="7d">Last 7 Days</option>
                      <option value="30d">Last 30 Days</option>
                      <option value="90d">Last 90 Days</option>
                      <option value="12m">Last 12 Months</option>
                    </select>
                    <a
                      href="/saas-admin/export/revenue"
                      className="btn-secondary"
                      download
                    >
                      <FAIcon name="download" /> Export Revenue CSV
                    </a>
                  </div>
                </div>

                <RevenueSVGChart points={loaderData?.revenueData?.points || []} />
              </div>
            </div>
          ) : activeView === "subscriptions" ? (
            /* VIEW 5: SUBSCRIPTIONS ANALYTICS */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Pro Plan ($79/mo)</span>
                  <div className="kpi-number">{loaderData?.adminKPIs?.planBreakdown?.PRO || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Starter Plan ($29/mo)</span>
                  <div className="kpi-number">{loaderData?.adminKPIs?.planBreakdown?.STARTER || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Free Plan</span>
                  <div className="kpi-number">{loaderData?.adminKPIs?.planBreakdown?.FREE || 0}</div>
                </div>
              </div>


              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Active Store Subscriptions</h3>
                </div>

                <div className="toolbar">
                  <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap", flex: 1 }}>
                    <input
                      type="text"
                      placeholder="Search domain..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="input-field"
                      style={{ minWidth: "220px" }}
                    />
                    <select
                      className="select-input"
                      value={planFilter}
                      onChange={(e) => { setPlanFilter(e.target.value); updateUrlFilter({ planFilter: e.target.value, view: "subscriptions" }); }}
                    >
                      <option value="ALL">All Plans</option>
                      {(loaderData?.adminPlans && loaderData.adminPlans.length > 0) ? (
                        loaderData.adminPlans.map((p: any) => (
                          <option key={p.planKey} value={p.planKey}>
                            {p.displayName} ({p.billingInterval === "ONE_TIME" ? (p.price === 0 ? "Free" : `$${p.price} One-time`) : `$${p.price}/mo`})
                          </option>
                        ))
                      ) : (
                        <>
                          <option value="FREE">Free</option>
                          <option value="STARTER">Starter ($29/mo)</option>
                          <option value="PRO">Pro ($79/mo)</option>
                        </>
                      )}
                    </select>
                    <button type="button" className="btn-secondary" onClick={() => updateUrlFilter({ search: searchQuery.trim(), view: "subscriptions" })}>Filter</button>
                    {(searchQuery || planFilter !== "ALL") && (
                      <button type="button" className="btn-secondary" onClick={() => { setSearchQuery(""); setPlanFilter("ALL"); updateUrlFilter({ search: "", planFilter: "ALL", view: "subscriptions" }); }}>Reset</button>
                    )}
                  </div>
                </div>

                <div className="table-responsive">
                  <table className="modern-table">
                    <thead>
                      <tr>
                        <th>Store Domain</th>
                        <th>Current Plan</th>
                        <th>Monthly Limit</th>
                        <th>Message Usage</th>
                        <th>Total Conversations</th>
                        <th>Price</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(loaderData?.adminStoresData?.stores || []).length === 0 ? (
                        <tr>
                          <td colSpan={7} style={{ textAlign: "center", padding: "40px 20px", color: "var(--text-secondary)" }}>
                            <FAIcon name="magnifying-glass" style={{ fontSize: "24px", color: "var(--text-muted)", marginBottom: "8px" }} />
                            <div style={{ fontWeight: 600, color: "var(--text-primary)", fontSize: "14px" }}>No results found</div>
                            <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "4px" }}>Try changing your search or filters.</div>
                            {(searchQuery || planFilter !== "ALL") && (
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ marginTop: "12px" }}
                                onClick={() => { setSearchQuery(""); setPlanFilter("ALL"); updateUrlFilter({ search: "", planFilter: "ALL", view: "subscriptions" }); }}
                              >
                                Clear filters
                              </button>
                            )}
                          </td>
                        </tr>
                      ) : (
                        (loaderData?.adminStoresData?.stores || []).map((s: any) => (
                          <tr key={s.id}>
                            <td><strong className="val-important">{s.shopifyDomain}</strong></td>
                            <td><span className="status-badge success">{s.plan}</span></td>
                            <td>{s.monthlyLimit} msgs</td>
                            <td>{s.currentUsage || 0} msgs {s.totalUsage && s.totalUsage > s.currentUsage ? `(${s.totalUsage} total)` : ""}</td>
                            <td><strong className="val-important">{s.conversationCount || 0} chats</strong></td>
                            <td><strong className="val-important">{s.billingType === "ONE_TIME" || s.plan === "FREE" || s.monthlyPrice === 0 ? (s.monthlyPrice === 0 ? "Free ($0.00)" : `$${(s.monthlyPrice || 0).toFixed(2)}`) : `$${(s.monthlyPrice || 0).toFixed(2)}/mo`}</strong></td>
                            <td>
                              <Link
                                to={`/saas-admin?view=subscriptions&modal=manage_plan&editShopId=${s.id}`}
                                className="btn-secondary"
                                style={{ height: "28px", padding: "0 10px", fontSize: "12px" }}
                                onClick={(e) => {
                                  e.preventDefault();
                                  setManagingSubStore(s);
                                }}
                              >
                                Manage Subscription
                              </Link>
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>

                <PaginationBar
                  page={loaderData?.adminStoresData?.page || 1}
                  totalPages={loaderData?.adminStoresData?.totalPages || 1}
                  totalCount={loaderData?.adminStoresData?.totalCount || 0}
                  onPageChange={(newPage) => updateUrlFilter({ page: newPage, view: "subscriptions" })}
                />
              </div>
            </div>
          ) : activeView === "plans" ? (
            /* VIEW 5B: PLANS & PRICING MANAGEMENT */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Total Configured Plans</span>
                  <div className="kpi-number">{loaderData?.adminPlans?.length || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Active Storefront Tiers</span>
                  <div className="kpi-number">
                    {(loaderData?.adminPlans || []).filter((p: any) => p.isActive).length}
                  </div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">AI-Enabled Plans</span>
                  <div className="kpi-number">
                    {(loaderData?.adminPlans || []).filter((p: any) => p.aiUsageEnabled).length}
                  </div>
                </div>
              </div>

              {/* ACTION BAR & HEADER */}
              <div className="card">
                <div className="card-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "12px" }}>
                  <div>
                    <h3 className="card-heading">Available Subscription Plans</h3>
                    <p style={{ margin: "4px 0 0 0", fontSize: "13px", color: "var(--text-secondary)" }}>
                      Dynamic tiers configured in database and available to merchants in their dashboard.
                    </p>
                  </div>
                  <button
                    type="button"
                    className="btn-primary"
                    onClick={() => setShowAddPlanModal(true)}
                    style={{ display: "flex", alignItems: "center", gap: "6px" }}
                  >
                    <FAIcon name="plus" /> + Add New Plan
                  </button>
                </div>

                {/* VISUAL CARDS GRID */}
                <div style={{ padding: "20px", display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: "20px" }}>
                  {(loaderData?.adminPlans || []).length === 0 ? (
                    <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: "40px", color: "var(--text-secondary)" }}>
                      No subscription plans found. Click "+ Add New Plan" to create your first tier.
                    </div>
                  ) : (
                    (loaderData?.adminPlans || []).map((plan: any) => (
                      <div
                        key={plan.id || plan.planKey}
                        style={{
                          border: plan.isActive ? "2px solid var(--border-light)" : "1px dashed var(--text-muted)",
                          borderRadius: "12px",
                          padding: "20px",
                          background: plan.isActive ? "var(--bg-surface)" : "var(--bg-subtle)",
                          display: "flex",
                          flexDirection: "column",
                          justifyContent: "space-between",
                          boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
                          opacity: plan.isActive ? 1 : 0.75,
                        }}
                      >
                        <div>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "10px" }}>
                            <span style={{ fontSize: "11px", fontWeight: 700, padding: "2px 8px", borderRadius: "6px", background: "#e0e7ff", color: "#3730a3" }}>
                              {plan.planKey}
                            </span>
                            <span className={`status-badge ${plan.isActive ? "success" : "pending"}`} style={{ fontSize: "11px" }}>
                              {plan.isActive ? "ACTIVE" : "INACTIVE"}
                            </span>
                          </div>

                          <h4 style={{ fontSize: "18px", fontWeight: 700, margin: "0 0 6px 0", color: "var(--text-primary)", display: "flex", alignItems: "center", gap: "8px" }}>
                            <FAIcon
                              name={plan.planKey === "PRO" ? "wand-magic-sparkles" : plan.planKey === "STARTER" ? "cart-shopping" : "cube"}
                              style={{ color: plan.planKey === "PRO" ? "#f59e0b" : plan.planKey === "STARTER" ? "#4f46e5" : "#64748b", fontSize: "16px" }}
                            />
                            <span>{plan.displayName}</span>
                          </h4>

                          <div style={{ fontSize: "24px", fontWeight: 800, color: "var(--brand-primary)", marginBottom: "6px" }}>
                            ${plan.price}
                            <span style={{ fontSize: "12px", color: "var(--text-secondary)", fontWeight: 500 }}>
                              /month
                            </span>
                          </div>

                          <div style={{ fontSize: "12px", fontWeight: 600, color: plan.planKey === "PRO" ? "#059669" : plan.planKey === "STARTER" ? "#0284c7" : "var(--text-secondary)", marginBottom: "12px", display: "flex", alignItems: "center", gap: "6px" }}>
                            {plan.planKey === "PRO" ? (
                              <>
                                <FAIcon name="microchip" style={{ color: "#059669" }} />
                                <span>AI Chatbot (OpenAI & Gemini BYOK)</span>
                              </>
                            ) : plan.planKey === "STARTER" ? (
                              <>
                                <FAIcon name="cart-shopping" style={{ color: "#0284c7" }} />
                                <span>Shopify Storefront API & Checkout</span>
                              </>
                            ) : (
                              <>
                                <FAIcon name="cube" style={{ color: "#64748b" }} />
                                <span>Shopify Catalog & Product Search</span>
                              </>
                            )}
                          </div>

                          <p style={{ fontSize: "12px", color: "var(--text-secondary)", lineHeight: 1.5, marginBottom: "14px" }}>
                            {plan.description}
                          </p>

                          <div style={{ borderTop: "1px solid var(--border-light)", paddingTop: "12px", marginBottom: "16px" }}>
                            <div style={{ fontSize: "11px", fontWeight: 700, textTransform: "uppercase", color: "var(--text-secondary)", marginBottom: "8px" }}>
                              Included Features:
                            </div>
                            <ul style={{ margin: 0, paddingLeft: "16px", fontSize: "12px", color: "var(--text-primary)", lineHeight: 1.6 }}>
                              {(plan.features || []).map((feat: string, idx: number) => (
                                <li key={idx}>{feat}</li>
                              ))}
                            </ul>
                          </div>
                        </div>

                        <div style={{ display: "flex", gap: "8px", borderTop: "1px solid var(--border-light)", paddingTop: "14px" }}>
                          <button
                            type="button"
                            className="btn-secondary"
                            style={{ flex: 1, height: "32px", fontSize: "12px" }}
                            onClick={() => setEditingPlan(plan)}
                          >
                            <FAIcon name="pen" size="sm" /> Edit
                          </button>

                          <Form method="post" style={{ margin: 0 }}>
                            <input type="hidden" name="_intent" value="toggle_plan_status" />
                            <input type="hidden" name="planId" value={plan.id} />
                            <input type="hidden" name="planKey" value={plan.planKey} />
                            <input type="hidden" name="isActive" value={plan.isActive ? "false" : "true"} />
                            <button
                              type="submit"
                              className="btn-secondary"
                              style={{ height: "32px", fontSize: "12px" }}
                              title={plan.isActive ? "Deactivate Plan" : "Activate Plan"}
                            >
                              {plan.isActive ? "Disable" : "Enable"}
                            </button>
                          </Form>

                          <button
                            type="button"
                            className="btn-secondary"
                            style={{ height: "32px", fontSize: "12px", color: "#dc2626", borderColor: "#fecaca" }}
                            onClick={() => setDeletingPlan(plan)}
                            title="Delete Plan"
                          >
                            <FAIcon name="trash" size="sm" />
                          </button>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>

              {/* DETAILED TABLE VIEW */}
              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Plan Configuration Details</h3>
                </div>
                <div className="table-responsive">
                  <table className="modern-table">
                    <thead>
                      <tr>
                        <th>Plan Key</th>
                        <th>Display Name</th>
                        <th>Price</th>
                        <th>Billing Cycle</th>
                        <th>AI Enabled</th>
                        <th>Monthly AI Limit</th>
                        <th>Status</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(loaderData?.adminPlans || []).map((p: any) => (
                        <tr key={p.id || p.planKey}>
                          <td><strong>{p.planKey}</strong></td>
                          <td>{p.displayName}</td>
                          <td><strong className="val-important">${p.price}</strong></td>
                          <td>{p.billingInterval === "ONE_TIME" ? "One-Time" : "Monthly Recurring"}</td>
                          <td>
                            <span className={`status-badge ${p.aiUsageEnabled ? "success" : "pending"}`}>
                              {p.aiUsageEnabled ? "YES" : "NO"}
                            </span>
                          </td>
                          <td>{p.aiMonthlyLimit ? `${p.aiMonthlyLimit.toLocaleString()} msgs` : "0 (Shopify only)"}</td>
                          <td>
                            <span className={`status-badge ${p.isActive ? "success" : "error"}`}>
                              {p.isActive ? "ACTIVE" : "INACTIVE"}
                            </span>
                          </td>
                          <td>
                            <div style={{ display: "flex", gap: "6px" }}>
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ height: "26px", padding: "0 8px", fontSize: "11px" }}
                                onClick={() => setEditingPlan(p)}
                              >
                                Edit
                              </button>
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ height: "26px", padding: "0 8px", fontSize: "11px", color: "#dc2626" }}
                                onClick={() => setDeletingPlan(p)}
                              >
                                Delete
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          ) : activeView === "helplines" ? (
            /* VIEW 5C: HELPLINES & SUPPORT MANAGEMENT */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Total Helplines</span>
                  <div className="kpi-number">{loaderData?.adminHelplines?.length || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Active Support Channels</span>
                  <div className="kpi-number">
                    {(loaderData?.adminHelplines || []).filter((h: any) => h.isActive).length}
                  </div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">24/7 Coverage Channels</span>
                  <div className="kpi-number">
                    {(loaderData?.adminHelplines || []).filter((h: any) => (h.hours || "").includes("24/7")).length}
                  </div>
                </div>
              </div>

              {/* ACTION BAR & HEADER */}
              <div className="card">
                <div className="card-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "12px" }}>
                  <div>
                    <h3 className="card-heading">Store Helplines &amp; Support Contacts</h3>
                    <p style={{ margin: "4px 0 0 0", fontSize: "13px", color: "var(--text-secondary)" }}>
                      Customer support phone numbers, technical escalation desks, and emails displayed to store merchants.
                    </p>
                  </div>
                  <button
                    type="button"
                    className="btn-primary"
                    onClick={() => setShowAddHelplineModal(true)}
                    style={{ display: "flex", alignItems: "center", gap: "6px" }}
                  >
                    <FAIcon name="plus" /> + Add New Helpline
                  </button>
                </div>

                {/* VISUAL CARDS GRID */}
                <div style={{ padding: "20px", display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: "20px" }}>
                  {(loaderData?.adminHelplines || []).length === 0 ? (
                    <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: "40px", color: "var(--text-secondary)" }}>
                      No support helplines configured. Click "+ Add New Helpline" to create one.
                    </div>
                  ) : (
                    (loaderData?.adminHelplines || []).map((hl: any) => (
                      <div
                        key={hl.id}
                        style={{
                          border: hl.isActive ? "2px solid var(--border-light)" : "1px dashed var(--text-muted)",
                          borderRadius: "12px",
                          padding: "20px",
                          background: hl.isActive ? "var(--bg-surface)" : "var(--bg-subtle)",
                          display: "flex",
                          flexDirection: "column",
                          justifyContent: "space-between",
                          boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
                          opacity: hl.isActive ? 1 : 0.75,
                        }}
                      >
                        <div>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "10px" }}>
                            <span style={{ fontSize: "11px", fontWeight: 700, padding: "2px 8px", borderRadius: "6px", background: "#dbeafe", color: "#1e40af" }}>
                              {hl.hours || "24/7 Support"}
                            </span>
                            <span className={`status-badge ${hl.isActive ? "success" : "pending"}`} style={{ fontSize: "11px" }}>
                              {hl.isActive ? "ACTIVE" : "INACTIVE"}
                            </span>
                          </div>

                          <h4 style={{ fontSize: "17px", fontWeight: 700, margin: "0 0 10px 0", color: "var(--text-primary)" }}>
                            {hl.department}
                          </h4>

                          <div style={{ display: "flex", flexDirection: "column", gap: "6px", marginBottom: "12px" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: "8px", fontSize: "13px", fontWeight: 600, color: "var(--text-primary)" }}>
                              <FAIcon name="phone" style={{ color: "#10b981", fontSize: "12px" }} />
                              <a href={`tel:${hl.phoneNumber.replace(/[^+\d]/g, "")}`} style={{ color: "inherit", textDecoration: "none" }}>
                                {hl.phoneNumber}
                              </a>
                            </div>
                            <div style={{ display: "flex", alignItems: "center", gap: "8px", fontSize: "13px", color: "var(--text-secondary)" }}>
                              <FAIcon name="envelope" style={{ color: "#6366f1", fontSize: "12px" }} />
                              <a href={`mailto:${hl.email}`} style={{ color: "inherit", textDecoration: "none" }}>
                                {hl.email}
                              </a>
                            </div>
                          </div>

                          {hl.description && (
                            <p style={{ fontSize: "12px", color: "var(--text-secondary)", lineHeight: 1.5, margin: "0 0 14px 0" }}>
                              {hl.description}
                            </p>
                          )}
                        </div>

                        <div style={{ display: "flex", gap: "8px", borderTop: "1px solid var(--border-light)", paddingTop: "14px" }}>
                          <button
                            type="button"
                            className="btn-secondary"
                            style={{ flex: 1, height: "32px", fontSize: "12px" }}
                            onClick={() => setEditingHelpline(hl)}
                          >
                            <FAIcon name="pen" size="sm" /> Edit
                          </button>

                          <Form method="post" style={{ margin: 0 }}>
                            <input type="hidden" name="_intent" value="toggle_helpline_status" />
                            <input type="hidden" name="helplineId" value={hl.id} />
                            <input type="hidden" name="isActive" value={hl.isActive ? "false" : "true"} />
                            <button
                              type="submit"
                              className="btn-secondary"
                              style={{ height: "32px", fontSize: "12px" }}
                              title={hl.isActive ? "Deactivate Helpline" : "Activate Helpline"}
                            >
                              {hl.isActive ? "Disable" : "Enable"}
                            </button>
                          </Form>

                          <button
                            type="button"
                            className="btn-secondary"
                            style={{ height: "32px", fontSize: "12px", color: "#dc2626", borderColor: "#fecaca" }}
                            onClick={() => setDeletingHelpline(hl)}
                            title="Delete Helpline"
                          >
                            <FAIcon name="trash" size="sm" />
                          </button>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>

              {/* DETAILED HELPLINE TABLE VIEW */}
              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Helpline Configuration Details</h3>
                </div>
                <div className="table-responsive">
                  <table className="modern-table">
                    <thead>
                      <tr>
                        <th>Department / Desk</th>
                        <th>Phone Number</th>
                        <th>Support Email</th>
                        <th>Operating Hours</th>
                        <th>Status</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(loaderData?.adminHelplines || []).map((h: any) => (
                        <tr key={h.id}>
                          <td><strong>{h.department}</strong></td>
                          <td>
                            <a href={`tel:${h.phoneNumber.replace(/[^+\d]/g, "")}`} style={{ color: "#059669", fontWeight: 600, textDecoration: "none" }}>
                              {h.phoneNumber}
                            </a>
                          </td>
                          <td>
                            <a href={`mailto:${h.email}`} style={{ color: "#4f46e5", textDecoration: "none" }}>
                              {h.email}
                            </a>
                          </td>
                          <td><span style={{ fontSize: "12px", color: "var(--text-secondary)" }}>{h.hours}</span></td>
                          <td>
                            <span className={`status-badge ${h.isActive ? "success" : "error"}`}>
                              {h.isActive ? "ACTIVE" : "INACTIVE"}
                            </span>
                          </td>
                          <td>
                            <div style={{ display: "flex", gap: "6px" }}>
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ height: "26px", padding: "0 8px", fontSize: "11px" }}
                                onClick={() => setEditingHelpline(h)}
                              >
                                Edit
                              </button>
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ height: "26px", padding: "0 8px", fontSize: "11px", color: "#dc2626" }}
                                onClick={() => setDeletingHelpline(h)}
                              >
                                Delete
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          ) : activeView === "transactions" ? (
            /* VIEW 6: TRANSACTIONS LOG */
            <div className="card">
              <div className="card-header" style={{ justifyContent: "flex-end" }}>
                <a
                  href={`/saas-admin/export/transactions${isUnmasked ? "?unmask=true" : ""}`}
                  className="btn-secondary"
                  download
                >
                  <FAIcon name="download" /> Export Transactions CSV
                </a>
              </div>

              <div className="toolbar">
                <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap", flex: 1 }}>
                  <input
                    type="text"
                    placeholder="Search transaction ID, domain, customer..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        updateUrlFilter({ search: searchQuery.trim(), view: "transactions" });
                      }
                    }}
                    className="input-field"
                    style={{ minWidth: "240px" }}
                  />
                  <select
                    className="select-input"
                    value={statusFilter}
                    onChange={(e) => { setStatusFilter(e.target.value); updateUrlFilter({ statusFilter: e.target.value, view: "transactions" }); }}
                  >
                    <option value="ALL">All Statuses</option>
                    <option value="SUCCESSFUL">SUCCESSFUL</option>
                    <option value="PENDING">PENDING</option>
                    <option value="FAILED">FAILED</option>
                  </select>
                  <select
                    className="select-input"
                    value={eventTypeFilter}
                    onChange={(e) => { setEventTypeFilter(e.target.value); updateUrlFilter({ eventTypeFilter: e.target.value, view: "transactions" }); }}
                  >
                    <option value="ALL">All Event Types</option>
                    <option value="SUBSCRIPTION_PAYMENT">Subscription Payments</option>
                    <option value="CREDIT_PURCHASE">AI Booster Credits</option>
                  </select>
                  <select
                    className="select-input"
                    value={sortBy}
                    onChange={(e) => { setSortBy(e.target.value); updateUrlFilter({ sortBy: e.target.value, view: "transactions" }); }}
                  >
                    <option value="date">Sort: Date</option>
                    <option value="amount">Sort: Amount</option>
                    <option value="domain">Sort: Domain</option>
                    <option value="status">Sort: Status</option>
                    <option value="id">Sort: ID</option>
                  </select>
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={() => {
                      const newDir = sortDir === "desc" ? "asc" : "desc";
                      setSortDir(newDir);
                      updateUrlFilter({ sortDir: newDir, view: "transactions" });
                    }}
                  >
                    {sortDir === "desc" ? "↓ Desc" : "↑ Asc"}
                  </button>
                  <button type="button" className="btn-secondary" onClick={() => updateUrlFilter({ search: searchQuery.trim(), view: "transactions" })}>Filter</button>
                  {(searchQuery || statusFilter !== "ALL" || eventTypeFilter !== "ALL") && (
                    <button type="button" className="btn-secondary" onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setEventTypeFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", eventTypeFilter: "ALL", view: "transactions" }); }}>Reset</button>
                  )}
                </div>
              </div>

              <div className="table-responsive">
                <table className="modern-table">
                  <thead>
                    <tr>
                      <th>Transaction ID</th>
                      <th>Store Domain</th>
                      <th>Merchant Account</th>
                      <th>Plan / Item</th>
                      <th>Subscription Reference</th>
                      <th>Amount Paid</th>
                      <th>Billing Authority</th>
                      <th>Status</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(loaderData?.transactionsData?.transactions || []).length === 0 ? (
                      <tr>
                        <td colSpan={9} style={{ textAlign: "center", padding: "40px 20px", color: "var(--text-secondary)" }}>
                          <FAIcon name="magnifying-glass" style={{ fontSize: "24px", color: "var(--text-muted)", marginBottom: "8px" }} />
                          <div style={{ fontWeight: 600, color: "var(--text-primary)", fontSize: "14px" }}>No transactions found</div>
                          <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "4px" }}>Try changing your search or filters.</div>
                          {(searchQuery || statusFilter !== "ALL" || eventTypeFilter !== "ALL") && (
                            <button
                              type="button"
                              className="btn-secondary"
                              style={{ marginTop: "12px" }}
                              onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setEventTypeFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", eventTypeFilter: "ALL", view: "transactions" }); }}
                            >
                              Clear filters
                            </button>
                          )}
                        </td>
                      </tr>
                    ) : (
                      (loaderData?.transactionsData?.transactions || []).map((t: any) => (
                        <tr key={t.id} style={{ cursor: "pointer" }} onClick={() => setSelectedTxModal(t)}>
                          <td>
                            <code style={{ fontFamily: "monospace", fontSize: "12px", color: "#4f46e5", fontWeight: 700 }}>
                              {t.id}
                            </code>
                          </td>
                          <td className="val-important">{t.storeDomain}</td>
                          <td><strong>{t.customerName || t.storeDomain}</strong></td>
                          <td>
                            <span style={{ fontSize: "13px", fontWeight: 500, color: "#1e293b" }}>
                              {t.type}
                            </span>
                          </td>
                          <td>
                            <div style={{ display: "flex", alignItems: "center", gap: "6px", fontSize: "12px", fontFamily: "monospace" }}>
                              <FAIcon name="shield-halved" style={{ color: "#4f46e5" }} />
                              <span>{t.subscriptionRef || "Shopify App Subscription"}</span>
                            </div>
                          </td>
                          <td>
                            <strong style={{ color: t.amount > 0 ? "#059669" : "#64748b", fontSize: "14px" }}>
                              ${typeof t.amount === "number" ? t.amount.toFixed(2) : "0.00"} {t.currency || "USD"}
                            </strong>
                          </td>
                          <td>
                            <span className="status-badge neutral" style={{ background: "#e0e7ff", color: "#3730a3", fontWeight: 600 }}>
                              <FAIcon name="shield-halved" style={{ marginRight: "4px" }} />
                              {t.paymentMethod || "Shopify Billing API"}
                            </span>
                          </td>
                          <td>
                            <span className={`status-badge ${t.status === "SUCCESSFUL" || t.status === "PAID" || t.status === "ACTIVE" ? "success" : t.status === "PENDING" ? "warning" : "neutral"}`}>
                              {t.status}
                            </span>
                          </td>
                          <td>
                            <button
                              type="button"
                              className="btn-secondary"
                              style={{ height: "28px", padding: "0 10px", fontSize: "12px" }}
                              onClick={(e) => {
                                e.stopPropagation();
                                setSelectedTxModal(t);
                              }}
                            >
                              View Receipt
                            </button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>

              <PaginationBar
                page={loaderData?.transactionsData?.page || 1}
                totalPages={loaderData?.transactionsData?.totalPages || 1}
                totalCount={loaderData?.transactionsData?.totalCount || 0}
                onPageChange={(newPage) => updateUrlFilter({ page: newPage, view: "transactions" })}
              />
            </div>
          ) : activeView === "analytics" ? (
            /* VIEW 7: SESSION ANALYTICS */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Knowledge Base Items</span>
                  <div className="kpi-number">{loaderData?.sessionAnalytics?.knowledgeCount || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Total AI Chat Sessions</span>
                  <div className="kpi-number">{loaderData?.sessionAnalytics?.totalSessions || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Total AI Messages</span>
                  <div className="kpi-number">{loaderData?.sessionAnalytics?.totalMessages || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Assisted Checkout Conversion</span>
                  <div className="kpi-number">{loaderData?.sessionAnalytics?.conversionRate || 0}%</div>
                </div>
              </div>

              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Session & Catalog Synchronization Metrics</h3>
                </div>
                <p className="page-description">
                  Product catalog caches and active AI chat sessions are synced continuously across all merchant stores.
                </p>
              </div>
            </div>
          ) : activeView === "settings" ? (
            /* VIEW 8: GLOBAL SAAS SETTINGS & SHOPIFY BILLING */
            <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
              {/* PRIMARY STORE & SHOPIFY PARTNER CONFIGURATION */}
              <div className="card">
                <div className="card-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "10px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                    <FAIcon name="store" style={{ fontSize: "18px", color: "var(--brand-primary)" }} />
                    <div>
                      <h3 className="card-heading">Primary Store & Shopify Partner Configuration</h3>
                      <p className="page-description">Configure your default store domain, partner dashboard, and production URLs for easy environment switching.</p>
                    </div>
                  </div>
                  <span className="status-badge success" style={{ display: "inline-flex", alignItems: "center", gap: "6px" }}>
                    <FAIcon name="circle-check" size="xs" /> Active Primary: {loaderData?.platformSettings?.defaultStoreDomain || "your-store.myshopify.com"}
                  </span>
                </div>

                <Form method="post" style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
                  <input type="hidden" name="_intent" value="save_platform_settings" />

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
                    {/* PRIMARY STORE DOMAIN */}
                    <div>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="store" size="sm" /> Default / Primary Store Domain
                      </label>
                      <input
                        type="text"
                        name="defaultStoreDomain"
                        defaultValue={loaderData?.platformSettings?.defaultStoreDomain || ""}
                        placeholder="e.g. your-store.myshopify.com"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                        required
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Fallback store domain for AI session resolution, demo preview, and standalone API queries.
                      </div>
                    </div>

                    {/* SHOPIFY APP HANDLE */}
                    <div>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="tag" size="sm" /> Shopify App Handle / Slug
                      </label>
                      <input
                        type="text"
                        name="appHandle"
                        defaultValue={loaderData?.platformSettings?.appHandle || "conversecart-14"}
                        placeholder="e.g. conversecart-14"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                        required
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Used to construct the official Shopify App Pricing URL: <code>admin.shopify.com/store/:store/charges/:handle/pricing_plans</code>.
                      </div>
                    </div>

                    {/* SHOPIFY PARTNER STORE URL */}
                    <div>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="screwdriver-wrench" size="sm" /> Partner Store Admin URL
                      </label>
                      <input
                        type="text"
                        name="partnerStoreUrl"
                        defaultValue={loaderData?.platformSettings?.partnerStoreUrl || "https://admin.shopify.com/store/quickstart-1a79b82e"}
                        placeholder="https://admin.shopify.com/store/your-store"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Direct URL to open Shopify Merchant Admin for the development / primary store.
                      </div>
                    </div>

                    {/* SHOPIFY PARTNER DASHBOARD URL */}
                    <div>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="briefcase" size="sm" /> Shopify Partner Dashboard URL
                      </label>
                      <input
                        type="text"
                        name="partnerDashboardUrl"
                        defaultValue={loaderData?.platformSettings?.partnerDashboardUrl || "https://partners.shopify.com/3678763"}
                        placeholder="https://partners.shopify.com/your-org-id"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Shopify Partners portal organization URL to manage apps, billing, and payouts.
                      </div>
                    </div>

                    {/* SHOPIFY APP STORE LISTING URL */}
                    <div>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="bag-shopping" size="sm" /> Shopify App Store Listing URL
                      </label>
                      <input
                        type="text"
                        name="appStoreListingUrl"
                        defaultValue={loaderData?.platformSettings?.appStoreListingUrl || "https://apps.shopify.com/shoppilot"}
                        placeholder="https://apps.shopify.com/your-app-slug"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Live Shopify App Store listing for merchants to install and review the app.
                      </div>
                    </div>

                    {/* APP PRODUCTION URL */}
                    <div style={{ gridColumn: "span 2" }}>
                      <label className="input-label" style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="globe" size="sm" /> Production Hosting / App URL
                      </label>
                      <input
                        type="text"
                        name="appProductionUrl"
                        defaultValue={loaderData?.platformSettings?.appProductionUrl || process.env.SHOPIFY_APP_URL || ""}
                        placeholder="SHOPIFY_APP_URL"
                        className="input-field"
                        style={{ width: "100%", fontFamily: "monospace", marginTop: "6px" }}
                      />
                      <div className="page-description" style={{ marginTop: "4px", fontSize: "12px" }}>
                        Base URL configured in Shopify Partner Dashboard app setup (Embedded App URL / Redirect URLs).
                      </div>
                    </div>
                  </div>

                  {/* QUICK ACCESS ACTION BUTTONS */}
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "12px", borderTop: "1px solid var(--border-subtle, #e2e8f0)", paddingTop: "16px" }}>
                    <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
                      {loaderData?.platformSettings?.defaultStoreDomain && (
                        <a
                          href={`https://${loaderData.platformSettings.defaultStoreDomain}`}
                          target="_blank"
                          rel="noreferrer"
                          className="btn-secondary"
                          style={{ textDecoration: "none", fontSize: "13px", display: "inline-flex", alignItems: "center", gap: "6px" }}
                        >
                          <FAIcon name="store" size="sm" /> Open Storefront
                          <FAIcon name="arrow-up-right-from-square" size="xs" />
                        </a>
                      )}
                      {loaderData?.platformSettings?.partnerStoreUrl && (
                        <a
                          href={loaderData.platformSettings.partnerStoreUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="btn-secondary"
                          style={{ textDecoration: "none", fontSize: "13px", display: "inline-flex", alignItems: "center", gap: "6px" }}
                        >
                          <FAIcon name="screwdriver-wrench" size="sm" /> Open Store Admin
                          <FAIcon name="arrow-up-right-from-square" size="xs" />
                        </a>
                      )}
                      {loaderData?.platformSettings?.partnerDashboardUrl && (
                        <a
                          href={loaderData.platformSettings.partnerDashboardUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="btn-secondary"
                          style={{ textDecoration: "none", fontSize: "13px", display: "inline-flex", alignItems: "center", gap: "6px" }}
                        >
                          <FAIcon name="briefcase" size="sm" /> Launch Partner Dashboard
                          <FAIcon name="arrow-up-right-from-square" size="xs" />
                        </a>
                      )}
                      {loaderData?.platformSettings?.appStoreListingUrl && (
                        <a
                          href={loaderData.platformSettings.appStoreListingUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="btn-secondary"
                          style={{ textDecoration: "none", fontSize: "13px", display: "inline-flex", alignItems: "center", gap: "6px" }}
                        >
                          <FAIcon name="bag-shopping" size="sm" /> View App Store Page
                          <FAIcon name="arrow-up-right-from-square" size="xs" />
                        </a>
                      )}
                    </div>

                    <button type="submit" className="btn-primary">
                      <FAIcon name="floppy-disk" /> Save Platform Settings
                    </button>
                  </div>
                </Form>
              </div>

              {/* SHOPIFY APP BILLING & SUBSCRIPTION LIFECYCLE */}
              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">
                    <FAIcon name="shield-halved" style={{ marginRight: "8px", color: "var(--brand-primary)" }} />
                    Shopify App Subscription &amp; Billing Authority
                  </h3>
                  <span className="status-badge success">
                    🟢 SHOPIFY-AUTHORITATIVE
                  </span>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                  <p className="page-description" style={{ margin: 0 }}>
                    Shopify is the sole billing and payment authority for all merchant subscriptions.
                    Subscriptions are purchased, billed, and managed directly through official Shopify-hosted checkout flows.
                  </p>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
                    <div style={{ border: "1px solid var(--border-default)", borderRadius: "8px", padding: "16px", background: "var(--bg-subtle)" }}>
                      <h4 style={{ fontSize: "14px", fontWeight: 700, color: "var(--text-primary)", marginBottom: "8px", display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="check-double" /> Authoritative Architecture
                      </h4>
                      <ul style={{ margin: 0, paddingLeft: "18px", fontSize: "13px", color: "var(--text-secondary)", lineHeight: "1.6" }}>
                        <li><strong>Purchases:</strong> Shopify App Subscription API (GraphQL)</li>
                        <li><strong>Invoicing &amp; Payouts:</strong> Handled by Shopify Partner Program</li>
                        <li><strong>Entitlements:</strong> Synchronized automatically to local database</li>
                        <li><strong>Security:</strong> Zero custom card collection, gateways, or PII storage</li>
                      </ul>
                    </div>

                    <div style={{ border: "1px solid var(--border-default)", borderRadius: "8px", padding: "16px", background: "var(--bg-subtle)" }}>
                      <h4 style={{ fontSize: "14px", fontWeight: 700, color: "var(--text-primary)", marginBottom: "8px", display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="tags" /> Server-Enforced Tiers
                      </h4>
                      <ul style={{ margin: 0, paddingLeft: "18px", fontSize: "13px", color: "var(--text-secondary)", lineHeight: "1.6" }}>
                        <li><strong>Free Plan:</strong> $0 / month (Standard features)</li>
                        <li><strong>Starter Plan:</strong> $29 / month (Expanded limits &amp; features)</li>
                        <li><strong>Pro Plan:</strong> $79 / month (BYOK, Uncapped intelligence)</li>
                        <li><strong>Billing Route:</strong> <code>/billing/subscribe</code></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>

              {/* SYSTEM SECURITY & INFRASTRUCTURE */}
              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">System Security & Infrastructure</h3>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                  <div>
                    <label className="input-label">Cryptographic Session Expiration</label>
                    <input type="text" className="input-field" value="8 Hours (HMAC-SHA256 Token)" disabled style={{ width: "100%" }} />
                  </div>
                  <div>
                    <label className="input-label">Rate Limiting Threshold</label>
                    <input type="text" className="input-field" value="5 Login Attempts / 15 Minutes" disabled style={{ width: "100%" }} />
                  </div>
                  <div>
                    <label className="input-label">Prisma Database Status</label>
                    <input type="text" className="input-field" value="Connected to MySQL (Production Schema)" disabled style={{ width: "100%" }} />
                  </div>
                </div>
              </div>
            </div>
          ) : (
            /* DEFAULT DASHBOARD & OVERVIEW */
            <>
              <div className="kpi-grid">
                <div className="kpi-card">
                  <span className="kpi-label">Total Revenue</span>
                  <div className="kpi-number">${(loaderData?.adminKPIs?.mrr || 0).toFixed(2)}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Installed Stores</span>
                  <div className="kpi-number">{loaderData?.adminKPIs?.totalStores || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Active Subscriptions</span>
                  <div className="kpi-number">{loaderData?.adminKPIs?.activeStores || 0}</div>
                </div>
                <div className="kpi-card">
                  <span className="kpi-label">Monthly Recurring Revenue</span>
                  <div className="kpi-number">${(loaderData?.adminKPIs?.mrr || 0).toFixed(2)}</div>
                </div>
              </div>

              <div className="card">
                <div className="card-header">
                  <h3 className="card-heading">Stores ({loaderData?.adminStoresData?.totalCount || 0})</h3>
                  <div style={{ display: "flex", gap: "10px" }}>
                    <a
                      href={`/saas-admin/export/stores${isUnmasked ? "?unmask=true" : ""}`}
                      className="btn-secondary"
                      download
                    >
                      <FAIcon name="download" /> Export Stores CSV
                    </a>
                    <Link
                      to="/saas-admin?view=dashboard&modal=add_store"
                      className="btn-primary"
                      onClick={(e) => {
                        e.preventDefault();
                        setShowAddStoreModal(true);
                      }}
                    >
                      <FAIcon name="plus" /> Add Store
                    </Link>
                  </div>
                </div>

                <div className="table-responsive">
                  <table className="modern-table">
                    <thead>
                      <tr>
                        <th>Store Domain</th>
                        <th>Status</th>
                        <th>Plan</th>
                        <th>MRR</th>
                        <th>Last Active</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(loaderData?.adminStoresData?.stores || []).length === 0 ? (
                        <tr>
                          <td colSpan={6} style={{ textAlign: "center", padding: "40px 20px", color: "var(--text-secondary)" }}>
                            <FAIcon name="magnifying-glass" style={{ fontSize: "24px", color: "var(--text-muted)", marginBottom: "8px" }} />
                            <div style={{ fontWeight: 600, color: "var(--text-primary)", fontSize: "14px" }}>No results found</div>
                            <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "4px" }}>Try changing your search or filters.</div>
                            {(searchQuery || statusFilter !== "ALL" || planFilter !== "ALL") && (
                              <button
                                type="button"
                                className="btn-secondary"
                                style={{ marginTop: "12px" }}
                                onClick={() => { setSearchQuery(""); setStatusFilter("ALL"); setPlanFilter("ALL"); updateUrlFilter({ search: "", statusFilter: "ALL", planFilter: "ALL" }); }}
                              >
                                Clear filters
                              </button>
                            )}
                          </td>
                        </tr>
                      ) : (
                        (loaderData?.adminStoresData?.stores || []).map((s: any) => (
                          <tr key={s.id}>
                            <td>
                              <strong className="val-important">{s.shopifyDomain}</strong>
                              <div className="page-description" style={{ fontSize: "11px" }}>{s.merchantEmail}</div>
                            </td>
                            <td>
                              <span className={`status-badge ${s.status === "ACTIVE" ? "success" : "error"}`}>
                                {s.status}
                              </span>
                            </td>
                            <td><span className="status-badge neutral">{s.plan}</span></td>
                            <td><span className="val-important">${(s.monthlyPrice || 0).toFixed(2)}</span></td>
                            <td>{s.lastActiveAt}</td>
                            <td>
                              <div style={{ display: "flex", gap: "6px" }}>
                                <Link
                                  to={`/saas-admin?view=dashboard&modal=edit_store&editShopId=${s.id}`}
                                  className="btn-secondary"
                                  style={{ height: "28px", padding: "0 10px", fontSize: "12px" }}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    setEditingStore(s);
                                  }}
                                >
                                  Edit
                                </Link>
                                <Link
                                  to={`/saas-admin?view=dashboard&modal=manage_plan&editShopId=${s.id}`}
                                  className="btn-secondary"
                                  style={{ height: "28px", padding: "0 10px", fontSize: "12px" }}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    setManagingSubStore(s);
                                  }}
                                >
                                  Plan
                                </Link>
                                <button
                                  type="button"
                                  className="btn-secondary"
                                  style={{ height: "28px", padding: "0 10px", fontSize: "12px", color: "#4f46e5", borderColor: "#c7d2fe" }}
                                  onClick={() => setAdjustStoreItem(s)}
                                >
                                  <FAIcon name="bolt" /> Credits
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          )}
        </main>
      </div>

      {/* MODAL 1: ADD STORE */}
      {activeAddStoreModal && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) handleCloseAddModal(); }}>
          <div className="modal-card">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="modal-title">+ Add New Shopify Merchant Store</h3>
              <Link
                to={`/saas-admin?view=${activeView}`}
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", textDecoration: "none", color: "var(--text-muted)" }}
                onClick={() => setShowAddStoreModal(false)}
              >
                ✕
              </Link>
            </div>
            <Form method="post" style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              <input type="hidden" name="_intent" value="create_store" />
              {actionData && !actionData.success && actionData.intent === "create_store" && actionData.message && (
                <div style={{ backgroundColor: "#FEE2E2", color: "#991B1B", border: "1px solid #FCA5A5", padding: "10px 14px", borderRadius: "8px", fontSize: "13px" }}>
                  ⚠️ {actionData.message}
                </div>
              )}
              <div>
                <label className="input-label">Shopify Domain *</label>
                <input type="text" name="shopifyDomain" placeholder="store-name.myshopify.com" className="input-field" style={{ width: "100%" }} required />
              </div>
              <div>
                <label className="input-label">Merchant Email</label>
                <input type="email" name="merchantEmail" placeholder="admin@store.com" className="input-field" style={{ width: "100%" }} />
              </div>
              <div>
                <label className="input-label">Initial Plan Tier</label>
                <select name="plan" className="select-input" style={{ width: "100%" }}>
                  {(loaderData?.adminPlans && loaderData.adminPlans.length > 0) ? (
                    loaderData.adminPlans.map((p: any) => (
                      <option key={p.planKey} value={p.planKey}>
                        {p.displayName} ({p.billingInterval === "ONE_TIME" ? (p.price === 0 ? "Free" : `$${p.price} One-time`) : `$${p.price}/mo`})
                      </option>
                    ))
                  ) : (
                    <>
                      <option value="FREE">Free</option>
                      <option value="STARTER">Starter ($29/mo)</option>
                      <option value="PRO">Pro ($79/mo)</option>
                    </>
                  )}
                </select>
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "8px" }}>
                <Link
                  to={`/saas-admin?view=${activeView}`}
                  className="btn-secondary"
                  onClick={() => setShowAddStoreModal(false)}
                >
                  Cancel
                </Link>
                <button type="submit" disabled={isSubmitting} className="btn-primary">{isSubmitting ? "Creating..." : "Onboard Store"}</button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 2: EDIT STORE */}
      {activeEditStore && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) handleCloseEditModal(); }}>
          <div className="modal-card">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="modal-title">Edit Store: {activeEditStore.shopifyDomain}</h3>
              <Link
                to={`/saas-admin?view=${activeView}`}
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", textDecoration: "none", color: "var(--text-muted)" }}
                onClick={() => setEditingStore(null)}
              >
                ✕
              </Link>
            </div>
            <Form method="post" style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              <input type="hidden" name="_intent" value="edit_store" />
              <input type="hidden" name="shopId" value={activeEditStore.id} />
              {actionData && !actionData.success && actionData.intent === "edit_store" && actionData.message && (
                <div style={{ backgroundColor: "#FEE2E2", color: "#991B1B", border: "1px solid #FCA5A5", padding: "10px 14px", borderRadius: "8px", fontSize: "13px" }}>
                  ⚠️ {actionData.message}
                </div>
              )}
              <div>
                <label className="input-label">Shopify Domain</label>
                <input type="text" name="shopifyDomain" defaultValue={activeEditStore.shopifyDomain} className="input-field" style={{ width: "100%" }} required />
              </div>
              <div>
                <label className="input-label">Merchant Name</label>
                <input type="text" name="merchantName" defaultValue={activeEditStore.merchantName} className="input-field" style={{ width: "100%" }} />
              </div>
              <div>
                <label className="input-label">Store Status</label>
                <select name="status" defaultValue={activeEditStore.status} className="select-input" style={{ width: "100%" }}>
                  <option value="ACTIVE">ACTIVE</option>
                  <option value="UNINSTALLED">UNINSTALLED</option>
                </select>
              </div>
              <div>
                <label className="input-label">Chatbot Status (SaaS Admin Control)</label>
                <select name="chatbotAdminStatus" defaultValue={activeEditStore.chatbotAdminDisabled ? "INACTIVE" : "ACTIVE"} className="select-input" style={{ width: "100%" }}>
                  <option value="ACTIVE">ACTIVE (Store merchant can show/hide chatbot)</option>
                  <option value="INACTIVE">INACTIVE / LOCKED (Store merchant cannot activate chatbot)</option>
                </select>
                <p style={{ fontSize: "11px", color: "var(--text-muted)", marginTop: "4px" }}>
                  When set to INACTIVE, the chatbot widget is forcefully deactivated on the storefront and locked in the merchant dashboard.
                </p>
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "8px" }}>
                <Link
                  to={`/saas-admin?view=${activeView}`}
                  className="btn-secondary"
                  onClick={() => setEditingStore(null)}
                >
                  Cancel
                </Link>
                <button type="submit" disabled={isSubmitting} className="btn-primary">{isSubmitting ? "Saving..." : "Save Store Changes"}</button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 3: MANAGE SUBSCRIPTION */}
      {activePlanStore && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) handleClosePlanModal(); }}>
          <div className="modal-card">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="modal-title">Manage Subscription: {activePlanStore.shopifyDomain}</h3>
              <Link
                to={`/saas-admin?view=${activeView}`}
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", textDecoration: "none", color: "var(--text-muted)" }}
                onClick={() => setManagingSubStore(null)}
              >
                ✕
              </Link>
            </div>
            <Form method="post" style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              <input type="hidden" name="_intent" value="update_subscription" />
              <input type="hidden" name="shopId" value={activePlanStore.id} />
              <div>
                <label className="input-label">Plan Tier</label>
                <select name="plan" defaultValue={activePlanStore.plan} className="select-input" style={{ width: "100%" }}>
                  {(loaderData?.adminPlans && loaderData.adminPlans.length > 0) ? (
                    loaderData.adminPlans.map((p: any) => (
                      <option key={p.planKey} value={p.planKey}>
                        {p.displayName} ({p.billingInterval === "ONE_TIME" ? (p.price === 0 ? "Free" : `$${p.price} One-time`) : `$${p.price}/mo`})
                      </option>
                    ))
                  ) : (
                    <>
                      <option value="FREE">Free</option>
                      <option value="STARTER">Starter ($29/mo)</option>
                      <option value="PRO">Pro ($79/mo)</option>
                    </>
                  )}
                </select>
              </div>
              <div>
                <label className="input-label">Monthly AI Message Limit (Pro only)</label>
                <input type="number" name="monthlyLimit" defaultValue={activePlanStore.monthlyLimit || (activePlanStore.plan === "PRO" ? 25000 : 0)} className="input-field" style={{ width: "100%" }} />
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "8px" }}>
                <Link
                  to={`/saas-admin?view=${activeView}`}
                  className="btn-secondary"
                  onClick={() => setManagingSubStore(null)}
                >
                  Cancel
                </Link>
                <button type="submit" disabled={isSubmitting} className="btn-primary">{isSubmitting ? "Updating..." : "Update Subscription DB"}</button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 4: MERCHANT STORE DETAILS & FEATURE ACCESS */}
      {activeStoreDetails && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) handleCloseDetailsModal(); }}>
          <div className="modal-card" style={{ maxWidth: "680px", width: "100%" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--border-light)", paddingBottom: "12px" }}>
              <div>
                <h3 className="modal-title" style={{ fontSize: "16px", fontWeight: 700 }}>
                  Merchant Account & Feature Access: {activeStoreDetails.shopifyDomain}
                </h3>
                <p className="page-description" style={{ fontSize: "12px", marginTop: "2px" }}>
                  Merchant: <strong>{activeStoreDetails.merchantName}</strong> ({activeStoreDetails.merchantEmail})
                </p>
              </div>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={handleCloseDetailsModal}
              >
                ✕
              </button>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "18px", marginTop: "14px", maxHeight: "500px", overflowY: "auto" }}>
              {/* SUBSCRIPTION & BILLING SUMMARY */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px", background: "var(--bg-app)", padding: "14px", borderRadius: "8px" }}>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Current Plan</span>
                  <div style={{ fontSize: "14px", fontWeight: 700, color: "var(--text-primary)" }}>{activeStoreDetails.planDisplayName || activeStoreDetails.plan}</div>
                </div>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Subscription Status</span>
                  <div><span className={`status-badge ${activeStoreDetails.status === "ACTIVE" ? "success" : "error"}`}>{activeStoreDetails.status}</span></div>
                </div>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Billing Type & Interval</span>
                  <div style={{ fontSize: "13px", fontWeight: 600 }}>{activeStoreDetails.billingType === "ONE_TIME" ? "One-time Purchase" : "Monthly Recurring"}</div>
                </div>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Plan Amount</span>
                  <div style={{ fontSize: "13px", fontWeight: 600 }}>${(activeStoreDetails.monthlyPrice || 0).toFixed(2)}</div>
                </div>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Purchase / Installed Date</span>
                  <div style={{ fontSize: "13px" }}>{activeStoreDetails.installedAt}</div>
                </div>
                <div>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Renewal Date</span>
                  <div style={{ fontSize: "13px" }}>{activeStoreDetails.renewalDate || "N/A"}</div>
                </div>
                <div style={{ gridColumn: "span 2" }}>
                  <span style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>AI Monthly Usage</span>
                  <div style={{ fontSize: "14px", fontWeight: 700, color: activeStoreDetails.plan === "PRO" ? "var(--brand-primary)" : "var(--text-secondary)" }}>
                    {activeStoreDetails.aiUsageDisplay || (activeStoreDetails.plan === "PRO" ? `${activeStoreDetails.currentUsage} / 25,000` : "N/A")}
                  </div>
                </div>
              </div>

              {/* CHATBOT PLATFORM STATUS */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--bg-app)", padding: "14px", borderRadius: "8px" }}>
                <div>
                  <div style={{ fontSize: "11px", textTransform: "uppercase", color: "var(--text-muted)", fontWeight: 600 }}>Chatbot Status (SaaS Admin Control)</div>
                  <div style={{ fontSize: "13px", fontWeight: 700, marginTop: "2px" }}>
                    {activeStoreDetails.chatbotAdminDisabled ? (
                      <span style={{ color: "var(--color-error)" }}>🚫 INACTIVE (Locked & Hidden by SaaS Admin)</span>
                    ) : activeStoreDetails.chatbotEnabled ? (
                      <span style={{ color: "var(--color-success)" }}>✓ ACTIVE (Enabled on Storefront)</span>
                    ) : (
                      <span style={{ color: "var(--color-warning)" }}>⏸ DISABLED (Turned off by Merchant)</span>
                    )}
                  </div>
                </div>
                <Form method="post" style={{ display: "inline" }}>
                  <input type="hidden" name="_intent" value="toggle_store_chatbot" />
                  <input type="hidden" name="shopId" value={activeStoreDetails.id} />
                  <input type="hidden" name="adminDisabled" value={activeStoreDetails.chatbotAdminDisabled ? "false" : "true"} />
                  <button
                    type="submit"
                    className="btn-secondary"
                    style={{ fontSize: "12px", padding: "6px 12px" }}
                  >
                    {activeStoreDetails.chatbotAdminDisabled ? "Unlock & Enable Bot" : "Lock & Deactivate Bot"}
                  </button>
                </Form>
              </div>

              {/* CENTRALIZED FEATURE ACCESS SECTION */}
              <div>
                <h4 style={{ fontSize: "13px", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--text-secondary)", marginBottom: "8px" }}>
                  Feature Access (Server-Enforced)
                </h4>
                <div style={{ border: "1px solid var(--border-light)", borderRadius: "8px", overflow: "hidden" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                    <tbody>
                      {[
                        { label: "Shopify Products", key: "shopify.products", enabled: activeStoreDetails.featureAccess?.["shopify.products"] ?? true },
                        { label: "Shopify Cart", key: "shopify.cart", enabled: activeStoreDetails.featureAccess?.["shopify.cart"] ?? (activeStoreDetails.plan !== "FREE") },
                        { label: "Shopify Checkout", key: "shopify.checkout", enabled: activeStoreDetails.featureAccess?.["shopify.checkout"] ?? (activeStoreDetails.plan !== "FREE") },
                        { label: "OpenAI API", key: "openai", enabled: activeStoreDetails.featureAccess?.["openai"] ?? (activeStoreDetails.plan === "PRO") },
                        { label: "AI Chatbot", key: "ai.chatbot", enabled: activeStoreDetails.featureAccess?.["ai.chatbot"] ?? (activeStoreDetails.plan === "PRO") },
                        { label: "AI Recommendations", key: "ai.recommendations", enabled: activeStoreDetails.featureAccess?.["ai.recommendations"] ?? (activeStoreDetails.plan === "PRO") },
                        { label: "AI Customer Support", key: "ai.support", enabled: activeStoreDetails.featureAccess?.["ai.support"] ?? (activeStoreDetails.plan === "PRO") },
                      ].map((feat, idx) => (
                        <tr key={feat.key} style={{ borderBottom: idx < 6 ? "1px solid var(--border-light)" : "none", backgroundColor: idx % 2 === 0 ? "#FFFFFF" : "#F9FAFB" }}>
                          <td style={{ padding: "8px 14px", fontWeight: 500 }}>{feat.label}</td>
                          <td style={{ padding: "8px 14px", textAlign: "right" }}>
                            {feat.enabled ? (
                              <span style={{ display: "inline-block", padding: "2px 8px", borderRadius: "12px", fontSize: "11px", fontWeight: 700, backgroundColor: "#D1FAE5", color: "#065F46" }}>
                                ENABLED
                              </span>
                            ) : (
                              <span style={{ display: "inline-block", padding: "2px 8px", borderRadius: "12px", fontSize: "11px", fontWeight: 700, backgroundColor: "#FEE2E2", color: "#991B1B" }}>
                                DISABLED
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "14px" }}>
              <button type="button" className="btn-secondary" onClick={handleCloseDetailsModal}>
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MODAL 5: HELP & PLATFORM GUIDE */}
      {showHelpModal && (
        <div className="modal-overlay" style={{ zIndex: 10000 }} onClick={() => setShowHelpModal(false)}>
          <div className="modal-card" style={{ maxWidth: "650px", width: "100%" }} onClick={(e) => e.stopPropagation()}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "1px solid var(--border-light)", paddingBottom: "14px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                <FAIcon name="book" /> ShopPilot AI SaaS Admin Help Guide
              </h3>
              <button type="button" style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }} onClick={() => setShowHelpModal(false)}>✕</button>
            </div>
            <div className="modal-content" style={{ display: "flex", flexDirection: "column", gap: "16px", maxHeight: "450px", overflowY: "auto" }}>
              <div>
                <h4 style={{ fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>1. Dashboard Overview</h4>
                <p>Monitor all active merchant stores, subscriptions, revenue KPIs, and AI chat sessions in real-time from your centralized SaaS admin panel.</p>
              </div>
              <div>
                <h4 style={{ fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>2. Merchant Store & Subscription Management</h4>
                <p>Onboard new stores using the "+ Add Store" action. Modify store domains, active status, or subscription plan tiers (Free, Starter, Growth, Pro). All mutations are executed via atomic Prisma database transactions and logged in audit trails.</p>
              </div>
              <div>
                <h4 style={{ fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>3. AI Integrations & Security</h4>
                <p>Configure OpenAI API (GPT-4o Mini, GPT-4o) or Google Gemini API (Gemini 3.6 Flash) providers. Credentials are stored securely using AES-256-GCM server-side encryption.</p>
              </div>
              <div>
                <h4 style={{ fontWeight: 600, color: "var(--text-primary)", marginBottom: "4px" }}>4. Data Exports</h4>
                <p>Export Stores, Customers, Transactions, and Revenue datasets directly as RFC 4180 compliant CSV files.</p>
              </div>
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <button type="button" className="btn-primary" onClick={() => setShowHelpModal(false)}>
                Close Help Guide
              </button>
            </div>
          </div>
        </div>
      )}

      {/* NOTIFICATION DETAILS MODAL */}
      {selectedNotification && (
        <div className="modal-overlay" style={{ zIndex: 1000 }} onClick={(e) => { if (e.target === e.currentTarget) setSelectedNotification(null); }}>
          <div className="modal-card" style={{ maxWidth: "550px", width: "100%" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--border-light)", paddingBottom: "12px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                <span style={{ color: selectedNotification.type === "success" ? "var(--color-success)" : selectedNotification.type === "warning" ? "var(--color-warning)" : selectedNotification.type === "error" ? "var(--color-error)" : "var(--color-info)", fontSize: "20px" }}>
                  <FAIcon name={selectedNotification.type === "success" ? "circle-check" : selectedNotification.type === "warning" ? "triangle-exclamation" : selectedNotification.type === "error" ? "circle-xmark" : "circle-info"} />
                </span>
                <h3 className="modal-title" style={{ margin: 0 }}>{selectedNotification.action}</h3>
              </div>
              <button type="button" className="btn-secondary" style={{ height: "28px", padding: "0 8px" }} onClick={() => setSelectedNotification(null)}>✕</button>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "14px", marginTop: "14px" }}>
              <div className="page-description" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>Store / Scope: <strong className="val-important">{selectedNotification.shopDomain || "System Global"}</strong></span>
                <span className={`status-badge ${selectedNotification.isRead ? "neutral" : "info"}`}>
                  {selectedNotification.isRead ? "READ" : "UNREAD"}
                </span>
              </div>

              <div className="page-description" style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: "8px" }}>
                <span>Type: <strong className="val-important">{selectedNotification.rawType || selectedNotification.type}</strong></span>
                <span>Created Date: <strong className="val-important">{selectedNotification.createdAt}</strong></span>
                <span>Updated Date: <strong className="val-important">{selectedNotification.updatedAt || selectedNotification.createdAt}</strong></span>
              </div>

              <div style={{ padding: "16px", borderRadius: "var(--radius-input)", backgroundColor: "var(--bg-subtle)", border: "1px solid var(--border-default)", fontSize: "13px", color: "var(--text-primary)", lineHeight: "1.6" }}>
                <strong style={{ display: "block", marginBottom: "4px" }}>Details & Message:</strong>
                {selectedNotification.message || selectedNotification.details}
              </div>

              <div style={{ padding: "14px", borderRadius: "var(--radius-input)", backgroundColor: "var(--bg-subtle)", border: "1px solid var(--border-default)", fontSize: "12px" }}>
                <strong style={{ color: "var(--text-secondary)" }}>Metadata & Audit Info:</strong>
                {selectedNotification.metadata && Object.keys(selectedNotification.metadata).length > 0 ? (
                  <pre style={{ marginTop: "6px", fontFamily: "monospace", fontSize: "11px", whiteSpace: "pre-wrap", color: "var(--text-primary)" }}>
                    {JSON.stringify(selectedNotification.metadata, null, 2)}
                  </pre>
                ) : (
                  <div style={{ color: "var(--text-muted)", fontStyle: "italic", marginTop: "4px" }}>No additional metadata available</div>
                )}
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "16px" }}>
              {selectedNotification.targetView && selectedNotification.targetView !== "notifications" && (
                <button
                  type="button"
                  className="btn-primary"
                  onClick={() => {
                    const target = selectedNotification.targetView;
                    setSelectedNotification(null);
                    updateUrlFilter({ view: target });
                  }}
                >
                  {selectedNotification.actionLabel ? (
                    selectedNotification.actionLabel
                  ) : (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: "6px" }}>
                      Go to {selectedNotification.targetView.toUpperCase()} Section <FAIcon name="arrow-right" size="xs" />
                    </span>
                  )}
                </button>
              )}
              <button type="button" className="btn-secondary" onClick={() => setSelectedNotification(null)}>
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MODAL 5: SHOPIFY SUBSCRIPTION RECEIPT DETAILS */}
      {selectedTxModal && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setSelectedTxModal(null); }}>
          <div className="modal-card" style={{ maxWidth: "520px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid var(--border-default)", paddingBottom: "12px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="shield-halved" style={{ color: "var(--brand-primary)" }} />
                Shopify Subscription Receipt Details
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setSelectedTxModal(null)}
              >
                ✕
              </button>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              <div style={{ padding: "16px", borderRadius: "10px", background: "linear-gradient(135deg, #EEF2FF 0%, #E0E7FF 100%)", border: "1px solid var(--brand-border)", textAlign: "center" }}>
                <div style={{ fontSize: "12px", color: "#4f46e5", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>Total Payment Amount</div>
                <div style={{ fontSize: "28px", fontWeight: 800, color: "#1e1b4b", marginTop: "4px" }}>
                  ${typeof selectedTxModal.amount === "number" ? selectedTxModal.amount.toFixed(2) : "29.00"} {selectedTxModal.currency || "USD"}
                </div>
                <span className="status-badge success" style={{ marginTop: "8px" }}>
                  ✓ {selectedTxModal.status || "SUCCESSFUL"}
                </span>
              </div>

              <div style={{ border: "1px solid var(--border-default)", borderRadius: "8px", padding: "16px", background: "#ffffff", display: "flex", flexDirection: "column", gap: "12px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Transaction ID:</span>
                  <code style={{ fontFamily: "monospace", fontWeight: 700, color: "#4f46e5" }}>{selectedTxModal.id}</code>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Shopify Domain:</span>
                  <strong className="val-important">{selectedTxModal.storeDomain}</strong>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Billing Authority:</span>
                  <span style={{ fontWeight: 600, color: "#3730a3" }}>🛡️ {selectedTxModal.paymentMethod || "Shopify Billing API"}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Merchant Account:</span>
                  <strong>{selectedTxModal.customerName || selectedTxModal.storeDomain}</strong>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Subscription Reference:</span>
                  <code style={{ fontFamily: "monospace" }}>{selectedTxModal.subscriptionRef || "Shopify App Subscription"}</code>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Billing Interval:</span>
                  <span>Monthly</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Subscription Plan:</span>
                  <span className="status-badge neutral">{selectedTxModal.type}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Payment Date:</span>
                  <span>{selectedTxModal.createdAt}</span>
                </div>
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "20px" }}>
              <button type="button" className="btn-primary" onClick={() => setSelectedTxModal(null)}>
                Close Receipt
              </button>
            </div>
          </div>
        </div>
      )}
      {/* MODAL 6: ADMIN MANUAL CREDIT ADJUSTMENT */}
      {adjustStoreItem && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setAdjustStoreItem(null); }}>
          <div className="modal-card">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="bolt" style={{ color: "var(--brand-primary)" }} />
                Admin Manual Credit Adjustment
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setAdjustStoreItem(null)}
              >
                ✕
              </button>
            </div>
            <p className="page-description" style={{ marginTop: "4px" }}>
              Adjust credits for store <strong>{adjustStoreItem.shopifyDomain}</strong>. Positive numbers add credits (additive rule), negative numbers deduct credits.
            </p>

            <Form method="post" onSubmit={() => setAdjustStoreItem(null)} style={{ display: "flex", flexDirection: "column", gap: "16px", marginTop: "16px" }}>
              <input type="hidden" name="_intent" value="admin_adjust_credits" />
              <input type="hidden" name="shopId" value={adjustStoreItem.id} />

              <div>
                <label className="input-label">Adjustment Credit Amount (+ / -) *</label>
                <input
                  type="number"
                  name="amount"
                  placeholder="e.g. +500 or -200"
                  className="input-field"
                  style={{ width: "100%", fontFamily: "monospace" }}
                  required
                />
                <div style={{ fontSize: "11px", color: "var(--text-secondary)", marginTop: "4px" }}>
                  Use +500 for customer support compensation or -200 for refund deductions.
                </div>
              </div>

              <div>
                <label className="input-label">Mandatory Audit Log Reason *</label>
                <input
                  type="text"
                  name="reason"
                  placeholder="e.g. Customer support compensation for system downtime"
                  className="input-field"
                  style={{ width: "100%" }}
                  required
                />
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "8px", borderTop: "1px solid var(--border-light)", paddingTop: "12px" }}>
                <button type="button" className="btn-secondary" onClick={() => setAdjustStoreItem(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary">
                  Confirm Credit Adjustment
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 7: ADD SUBSCRIPTION PLAN */}
      {showAddPlanModal && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setShowAddPlanModal(false); }}>
          <div className="modal-card" style={{ maxWidth: "600px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid var(--border-default)", paddingBottom: "12px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="tags" style={{ color: "var(--brand-primary)" }} />
                + Create New Subscription Plan
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setShowAddPlanModal(false)}
              >
                ✕
              </button>
            </div>

            <Form method="post" onSubmit={() => setShowAddPlanModal(false)} style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
              <input type="hidden" name="_intent" value="create_plan" />

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Plan Unique Key *</label>
                  <input
                    type="text"
                    name="planKey"
                    placeholder="e.g. ENTERPRISE, GROWTH"
                    className="input-field"
                    style={{ width: "100%", textTransform: "uppercase" }}
                    required
                  />
                  <div style={{ fontSize: "11px", color: "var(--text-secondary)", marginTop: "2px" }}>Uppercase identifier (no spaces)</div>
                </div>

                <div>
                  <label className="input-label">Display Name *</label>
                  <input
                    type="text"
                    name="displayName"
                    placeholder="e.g. Enterprise Plan"
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Price ($ USD) *</label>
                  <input
                    type="number"
                    step="0.01"
                    name="price"
                    placeholder="29.00"
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>

                <div>
                  <label className="input-label">Billing Cycle *</label>
                  <select name="billingInterval" className="select-input" style={{ width: "100%" }}>
                    <option value="MONTHLY">Monthly Recurring ($/mo)</option>
                    <option value="ONE_TIME">One-Time App Purchase</option>
                  </select>
                </div>
              </div>

              <div style={{ border: "1px solid var(--border-light)", borderRadius: "8px", padding: "12px", background: "var(--bg-subtle)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" }}>
                  <input type="checkbox" name="aiUsageEnabled" id="add_aiUsageEnabled" defaultChecked value="true" />
                  <label htmlFor="add_aiUsageEnabled" style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", cursor: "pointer" }}>
                    Enable AI Sales Assistant & Quotas (OpenAI / Gemini)
                  </label>
                </div>
                <div>
                  <label className="input-label">Monthly AI Message Limit (msgs/mo)</label>
                  <input
                    type="number"
                    name="aiMonthlyLimit"
                    defaultValue="25000"
                    className="input-field"
                    style={{ width: "100%" }}
                  />
                  <div style={{ fontSize: "11px", color: "var(--text-secondary)", marginTop: "2px" }}>Leave empty or 0 for basic Shopify API plans without AI.</div>
                </div>
              </div>

              <div>
                <label className="input-label">Plan Description *</label>
                <textarea
                  name="description"
                  rows={2}
                  placeholder="Short overview shown on merchant pricing cards..."
                  className="input-field"
                  style={{ width: "100%", resize: "vertical" }}
                  required
                />
              </div>

              <div>
                <label className="input-label">Feature Bullet Points (one per line) *</label>
                <textarea
                  name="features"
                  rows={4}
                  placeholder="Everything in Starter tier&#10;OpenAI & Gemini AI Features&#10;Intelligent AI chatbot assistant&#10;Priority throughput"
                  className="input-field"
                  style={{ width: "100%", resize: "vertical", fontFamily: "inherit" }}
                  required
                />
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <input type="checkbox" name="isActive" id="add_isActive" defaultChecked value="true" />
                <label htmlFor="add_isActive" style={{ fontSize: "13px", color: "var(--text-primary)", cursor: "pointer" }}>
                  Active (Immediately visible to merchants in dashboard)
                </label>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "10px", borderTop: "1px solid var(--border-light)", paddingTop: "12px" }}>
                <button type="button" className="btn-secondary" onClick={() => setShowAddPlanModal(false)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary">
                  Save & Publish Plan
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 8: EDIT SUBSCRIPTION PLAN */}
      {editingPlan && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setEditingPlan(null); }}>
          <div className="modal-card" style={{ maxWidth: "600px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid var(--border-default)", paddingBottom: "12px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="pen" style={{ color: "var(--brand-primary)" }} />
                Edit Plan: {editingPlan.displayName} ({editingPlan.planKey})
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setEditingPlan(null)}
              >
                ✕
              </button>
            </div>

            <Form method="post" onSubmit={() => setEditingPlan(null)} style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
              <input type="hidden" name="_intent" value="edit_plan" />
              <input type="hidden" name="planId" value={editingPlan.id} />
              <input type="hidden" name="planKey" value={editingPlan.planKey} />

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Plan Identifier (Key)</label>
                  <input
                    type="text"
                    defaultValue={editingPlan.planKey}
                    className="input-field"
                    style={{ width: "100%", backgroundColor: "var(--bg-subtle)" }}
                    disabled
                  />
                </div>

                <div>
                  <label className="input-label">Display Name *</label>
                  <input
                    type="text"
                    name="displayName"
                    defaultValue={editingPlan.displayName}
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Price ($ USD) *</label>
                  <input
                    type="number"
                    step="0.01"
                    name="price"
                    defaultValue={editingPlan.price}
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>

                <div>
                  <label className="input-label">Billing Cycle *</label>
                  <select name="billingInterval" defaultValue={editingPlan.billingInterval} className="select-input" style={{ width: "100%" }}>
                    <option value="MONTHLY">Monthly Recurring ($/mo)</option>
                    <option value="ONE_TIME">One-Time App Purchase</option>
                  </select>
                </div>
              </div>

              <div style={{ border: "1px solid var(--border-light)", borderRadius: "8px", padding: "12px", background: "var(--bg-subtle)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" }}>
                  <input
                    type="checkbox"
                    name="aiUsageEnabled"
                    id="edit_aiUsageEnabled"
                    defaultChecked={editingPlan.aiUsageEnabled}
                    value="true"
                  />
                  <label htmlFor="edit_aiUsageEnabled" style={{ fontSize: "13px", fontWeight: 600, color: "var(--text-primary)", cursor: "pointer" }}>
                    Enable AI Sales Assistant & Quotas (OpenAI / Gemini)
                  </label>
                </div>
                <div>
                  <label className="input-label">Monthly AI Message Limit (msgs/mo)</label>
                  <input
                    type="number"
                    name="aiMonthlyLimit"
                    defaultValue={editingPlan.aiMonthlyLimit || 0}
                    className="input-field"
                    style={{ width: "100%" }}
                  />
                </div>
              </div>

              <div>
                <label className="input-label">Plan Description *</label>
                <textarea
                  name="description"
                  rows={2}
                  defaultValue={editingPlan.description}
                  className="input-field"
                  style={{ width: "100%", resize: "vertical" }}
                  required
                />
              </div>

              <div>
                <label className="input-label">Feature Bullet Points (one per line) *</label>
                <textarea
                  name="features"
                  rows={4}
                  defaultValue={(editingPlan.features || []).join("\n")}
                  className="input-field"
                  style={{ width: "100%", resize: "vertical", fontFamily: "inherit" }}
                  required
                />
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <input
                  type="checkbox"
                  name="isActive"
                  id="edit_isActive"
                  defaultChecked={editingPlan.isActive}
                  value="true"
                />
                <label htmlFor="edit_isActive" style={{ fontSize: "13px", color: "var(--text-primary)", cursor: "pointer" }}>
                  Active (Visible to merchants in subscription options)
                </label>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "10px", borderTop: "1px solid var(--border-light)", paddingTop: "12px" }}>
                <button type="button" className="btn-secondary" onClick={() => setEditingPlan(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary">
                  Save Changes
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL 9: DELETE SUBSCRIPTION PLAN CONFIRMATION */}
      {deletingPlan && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setDeletingPlan(null); }}>
          <div className="modal-card" style={{ maxWidth: "480px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px", borderBottom: "1px solid #fee2e2", paddingBottom: "10px" }}>
              <h3 className="modal-title" style={{ color: "#dc2626", display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="triangle-exclamation" />
                Confirm Plan Deletion
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setDeletingPlan(null)}
              >
                ✕
              </button>
            </div>

            <p style={{ fontSize: "14px", color: "var(--text-primary)", lineHeight: 1.5 }}>
              Are you sure you want to permanently delete plan <strong>{deletingPlan.displayName}</strong> (<code>{deletingPlan.planKey}</code>)?
            </p>
            <p style={{ fontSize: "12px", color: "var(--text-secondary)", marginTop: "6px" }}>
              This plan will no longer be offered to merchants in their dashboard subscription modal.
            </p>

            <Form method="post" onSubmit={() => setDeletingPlan(null)} style={{ marginTop: "16px" }}>
              <input type="hidden" name="_intent" value="delete_plan" />
              <input type="hidden" name="planId" value={deletingPlan.id} />

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px" }}>
                <button type="button" className="btn-secondary" onClick={() => setDeletingPlan(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary" style={{ backgroundColor: "#dc2626", borderColor: "#dc2626" }}>
                  Delete Plan
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL: ADD NEW HELPLINE */}
      {showAddHelplineModal && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setShowAddHelplineModal(false); }}>
          <div className="modal-card" style={{ maxWidth: "560px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid var(--border-default)", paddingBottom: "12px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="headset" style={{ color: "var(--brand-primary)" }} />
                Add New Support Helpline
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setShowAddHelplineModal(false)}
              >
                ✕
              </button>
            </div>

            <Form method="post" onSubmit={() => setShowAddHelplineModal(false)} style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
              <input type="hidden" name="_intent" value="create_helpline" />

              <div>
                <label className="input-label">Department / Desk Name *</label>
                <input
                  type="text"
                  name="department"
                  placeholder="e.g. Customer Support Helpline, Technical Escalation"
                  className="input-field"
                  style={{ width: "100%" }}
                  required
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Helpline Phone Number *</label>
                  <input
                    type="text"
                    name="phoneNumber"
                    placeholder="e.g. +91 8000361445"
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
                <div>
                  <label className="input-label">Support Email Address *</label>
                  <input
                    type="email"
                    name="email"
                    placeholder="e.g. ashvin@digihorizon.in"
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Operating Hours / Availability *</label>
                  <input
                    type="text"
                    name="hours"
                    defaultValue="24/7 Priority Support"
                    placeholder="e.g. Mon - Fri: 9:00 AM - 6:00 PM EST"
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
                <div>
                  <label className="input-label">Sort Order</label>
                  <input
                    type="number"
                    name="sortOrder"
                    defaultValue={1}
                    className="input-field"
                    style={{ width: "100%" }}
                  />
                </div>
              </div>

              <div>
                <label className="input-label">Description / Scope (Optional)</label>
                <textarea
                  name="description"
                  rows={2}
                  placeholder="Toll-free customer support helpline for order assistance, shipping queries, and store help."
                  className="input-field"
                  style={{ width: "100%", resize: "vertical" }}
                />
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <input
                  type="checkbox"
                  name="isActive"
                  id="add_hl_isActive"
                  defaultChecked={true}
                  value="true"
                />
                <label htmlFor="add_hl_isActive" style={{ fontSize: "13px", color: "var(--text-primary)", cursor: "pointer" }}>
                  Active (Visible to store merchants in their helpline section)
                </label>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "10px", borderTop: "1px solid var(--border-light)", paddingTop: "12px" }}>
                <button type="button" className="btn-secondary" onClick={() => setShowAddHelplineModal(false)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary">
                  + Create Helpline
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL: EDIT HELPLINE */}
      {editingHelpline && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setEditingHelpline(null); }}>
          <div className="modal-card" style={{ maxWidth: "560px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid var(--border-default)", paddingBottom: "12px" }}>
              <h3 className="modal-title" style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="pen" style={{ color: "var(--brand-primary)" }} />
                Edit Support Helpline: {editingHelpline.department}
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setEditingHelpline(null)}
              >
                ✕
              </button>
            </div>

            <Form method="post" onSubmit={() => setEditingHelpline(null)} style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
              <input type="hidden" name="_intent" value="edit_helpline" />
              <input type="hidden" name="helplineId" value={editingHelpline.id} />

              <div>
                <label className="input-label">Department / Desk Name *</label>
                <input
                  type="text"
                  name="department"
                  defaultValue={editingHelpline.department}
                  className="input-field"
                  style={{ width: "100%" }}
                  required
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Helpline Phone Number *</label>
                  <input
                    type="text"
                    name="phoneNumber"
                    defaultValue={editingHelpline.phoneNumber}
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
                <div>
                  <label className="input-label">Support Email Address *</label>
                  <input
                    type="email"
                    name="email"
                    defaultValue={editingHelpline.email}
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: "12px" }}>
                <div>
                  <label className="input-label">Operating Hours / Availability *</label>
                  <input
                    type="text"
                    name="hours"
                    defaultValue={editingHelpline.hours || "24/7 Support"}
                    className="input-field"
                    style={{ width: "100%" }}
                    required
                  />
                </div>
                <div>
                  <label className="input-label">Sort Order</label>
                  <input
                    type="number"
                    name="sortOrder"
                    defaultValue={editingHelpline.sortOrder ?? 1}
                    className="input-field"
                    style={{ width: "100%" }}
                  />
                </div>
              </div>

              <div>
                <label className="input-label">Description / Scope (Optional)</label>
                <textarea
                  name="description"
                  rows={2}
                  defaultValue={editingHelpline.description || ""}
                  className="input-field"
                  style={{ width: "100%", resize: "vertical" }}
                />
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <input
                  type="checkbox"
                  name="isActive"
                  id="edit_hl_isActive"
                  defaultChecked={editingHelpline.isActive}
                  value="true"
                />
                <label htmlFor="edit_hl_isActive" style={{ fontSize: "13px", color: "var(--text-primary)", cursor: "pointer" }}>
                  Active (Visible to store merchants in their helpline section)
                </label>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "10px", borderTop: "1px solid var(--border-light)", paddingTop: "12px" }}>
                <button type="button" className="btn-secondary" onClick={() => setEditingHelpline(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary">
                  Save Changes
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}

      {/* MODAL: DELETE HELPLINE CONFIRMATION */}
      {deletingHelpline && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setDeletingHelpline(null); }}>
          <div className="modal-card" style={{ maxWidth: "480px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px", borderBottom: "1px solid #fee2e2", paddingBottom: "10px" }}>
              <h3 className="modal-title" style={{ color: "#dc2626", display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="triangle-exclamation" />
                Confirm Helpline Deletion
              </h3>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "18px", color: "var(--text-muted)" }}
                onClick={() => setDeletingHelpline(null)}
              >
                ✕
              </button>
            </div>

            <p style={{ fontSize: "14px", color: "var(--text-primary)", lineHeight: 1.5 }}>
              Are you sure you want to delete helpline <strong>{deletingHelpline.department}</strong> ({deletingHelpline.phoneNumber})?
            </p>
            <p style={{ fontSize: "12px", color: "var(--text-secondary)", marginTop: "6px" }}>
              This helpline will no longer be displayed on store merchant dashboards.
            </p>

            <Form method="post" onSubmit={() => setDeletingHelpline(null)} style={{ marginTop: "16px" }}>
              <input type="hidden" name="_intent" value="delete_helpline" />
              <input type="hidden" name="helplineId" value={deletingHelpline.id} />

              <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px" }}>
                <button type="button" className="btn-secondary" onClick={() => setDeletingHelpline(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary" style={{ backgroundColor: "#dc2626", borderColor: "#dc2626" }}>
                  Delete Helpline
                </button>
              </div>
            </Form>
          </div>
        </div>
      )}
      {/* MODAL 10: TRANSACTION RECEIPT / DETAILS MODAL */}
      {selectedTxModal && (
        <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) setSelectedTxModal(null); }}>
          <div className="modal-card" style={{ maxWidth: "620px", padding: "24px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "20px", borderBottom: "1px solid var(--border-default)", paddingBottom: "16px" }}>
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                  <span style={{ fontSize: "12px", fontWeight: 700, letterSpacing: "0.05em", color: "#4f46e5", textTransform: "uppercase" }}>
                    Official Billing Receipt
                  </span>
                  <span className={`status-badge ${selectedTxModal.status === "SUCCESSFUL" || selectedTxModal.status === "PAID" || selectedTxModal.status === "ACTIVE" ? "success" : selectedTxModal.status === "PENDING" ? "warning" : "neutral"}`}>
                    {selectedTxModal.status}
                  </span>
                </div>
                <h3 className="modal-title" style={{ marginTop: "4px", fontSize: "18px", display: "flex", alignItems: "center", gap: "8px" }}>
                  <FAIcon name="receipt" style={{ color: "#4f46e5" }} />
                  Transaction {selectedTxModal.id}
                </h3>
              </div>
              <button
                type="button"
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: "20px", color: "var(--text-muted)" }}
                onClick={() => setSelectedTxModal(null)}
              >
                ✕
              </button>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "20px", background: "var(--bg-subtle)", padding: "16px", borderRadius: "10px", border: "1px solid var(--border-light)" }}>
              <div>
                <div style={{ fontSize: "11px", fontWeight: 700, color: "var(--text-secondary)", textTransform: "uppercase", marginBottom: "4px" }}>
                  Billed To
                </div>
                <div style={{ fontWeight: 600, fontSize: "14px", color: "var(--text-primary)" }}>
                  {selectedTxModal.customerName || selectedTxModal.storeDomain}
                </div>
                <div style={{ fontSize: "13px", color: "var(--text-secondary)", marginTop: "2px" }}>
                  {selectedTxModal.storeDomain}
                </div>
                <div style={{ fontSize: "12px", color: "var(--text-muted)", marginTop: "2px", fontFamily: "monospace" }}>
                  {selectedTxModal.customerEmail}
                </div>
              </div>

              <div>
                <div style={{ fontSize: "11px", fontWeight: 700, color: "var(--text-secondary)", textTransform: "uppercase", marginBottom: "4px" }}>
                  Billing Info
                </div>
                <div style={{ fontSize: "13px", color: "var(--text-primary)", fontWeight: 500 }}>
                  <span style={{ color: "var(--text-secondary)" }}>Invoice #:</span> <strong>{selectedTxModal.invoiceNumber || "N/A"}</strong>
                </div>
                <div style={{ fontSize: "13px", color: "var(--text-primary)", marginTop: "2px" }}>
                  <span style={{ color: "var(--text-secondary)" }}>Authority:</span> {selectedTxModal.paymentMethod || "Shopify Billing API"}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: "6px", fontSize: "12px", fontFamily: "monospace", marginTop: "4px", color: "#4f46e5" }}>
                  <FAIcon name="shield-halved" />
                  <span>{selectedTxModal.subscriptionRef || "Shopify App Subscription"}</span>
                </div>
                <div style={{ fontSize: "12px", color: "var(--text-muted)", marginTop: "4px" }}>
                  {selectedTxModal.createdAt}
                </div>
              </div>
            </div>

            <div style={{ border: "1px solid var(--border-light)", borderRadius: "10px", overflow: "hidden", marginBottom: "20px" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                <thead>
                  <tr style={{ background: "var(--bg-subtle)", borderBottom: "1px solid var(--border-light)", textAlign: "left" }}>
                    <th style={{ padding: "10px 14px", fontWeight: 600, color: "var(--text-secondary)" }}>Item Description</th>
                    <th style={{ padding: "10px 14px", fontWeight: 600, color: "var(--text-secondary)" }}>Type</th>
                    <th style={{ padding: "10px 14px", fontWeight: 600, color: "var(--text-secondary)", textAlign: "right" }}>Amount</th>
                  </tr>
                </thead>
                <tbody>
                  <tr style={{ borderBottom: "1px solid var(--border-light)" }}>
                    <td style={{ padding: "12px 14px", fontWeight: 600, color: "var(--text-primary)" }}>
                      {selectedTxModal.type}
                    </td>
                    <td style={{ padding: "12px 14px", color: "var(--text-secondary)" }}>
                      {selectedTxModal.eventType || "SUBSCRIPTION_PAYMENT"}
                    </td>
                    <td style={{ padding: "12px 14px", textAlign: "right", fontWeight: 700, color: "var(--text-primary)" }}>
                      ${typeof selectedTxModal.amount === "number" ? selectedTxModal.amount.toFixed(2) : "0.00"} {selectedTxModal.currency || "USD"}
                    </td>
                  </tr>
                </tbody>
              </table>

              <div style={{ padding: "12px 14px", background: "var(--bg-subtle)", display: "flex", flexDirection: "column", gap: "6px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", color: "var(--text-secondary)" }}>
                  <span>Subtotal:</span>
                  <span>${typeof selectedTxModal.amount === "number" ? selectedTxModal.amount.toFixed(2) : "0.00"} {selectedTxModal.currency || "USD"}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", color: "var(--text-secondary)" }}>
                  <span>Taxes & Fees (0%):</span>
                  <span>$0.00</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "15px", fontWeight: 700, color: "#059669", borderTop: "1px solid var(--border-light)", paddingTop: "8px", marginTop: "4px" }}>
                  <span>Total Amount Paid:</span>
                  <span>${typeof selectedTxModal.amount === "number" ? selectedTxModal.amount.toFixed(2) : "0.00"} {selectedTxModal.currency || "USD"}</span>
                </div>
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid var(--border-light)", paddingTop: "14px" }}>
              <button
                type="button"
                className="btn-secondary"
                onClick={() => window.print()}
                style={{ display: "flex", alignItems: "center", gap: "6px" }}
              >
                <FAIcon name="print" />
                Print Receipt
              </button>
              <button
                type="button"
                className="btn-primary"
                onClick={() => setSelectedTxModal(null)}
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export function ErrorBoundary() {
  const error: any = useRouteError();
  console.error("[SaaS Admin ErrorBoundary]:", error);
  const errorMessage = error?.message || error?.data?.message || (typeof error === "string" ? error : "An unexpected server error occurred.");

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "#F8FAFC", padding: "20px", fontFamily: "sans-serif" }}>
      <div style={{ backgroundColor: "#FFFFFF", borderRadius: "12px", width: "100%", maxWidth: "480px", padding: "36px", boxShadow: "0 4px 16px rgba(0,0,0,0.08)", textAlign: "center", border: "1px solid #E2E8F0" }}>
        <div style={{ width: "48px", height: "48px", borderRadius: "12px", backgroundColor: "#FEE2E2", color: "#DC2626", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px", fontSize: "20px", fontWeight: "bold" }}>
          ⚠️
        </div>
        <h2 style={{ color: "#0F172A", margin: "0 0 8px 0", fontSize: "20px", fontWeight: 700 }}>SaaS Admin Portal</h2>
        <p style={{ color: "#EF4444", marginTop: "12px", fontFamily: "monospace", fontSize: "13px", background: "#FEF2F2", padding: "10px 12px", borderRadius: "8px", border: "1px solid #FEE2E2", wordBreak: "break-word" }}>
          {errorMessage}
        </p>
        <div style={{ display: "flex", gap: "10px", justifyContent: "center", marginTop: "20px" }}>
          <button
            type="button"
            onClick={() => { window.location.href = "/saas-admin"; }}
            style={{ padding: "10px 18px", borderRadius: "8px", backgroundColor: "#4F46E5", color: "#FFF", border: "none", cursor: "pointer", fontWeight: 600, fontSize: "14px" }}
          >
            Dashboard
          </button>
          <button
            type="button"
            onClick={() => { window.location.href = "/saas-admin?view=integrations"; }}
            style={{ padding: "10px 18px", borderRadius: "8px", backgroundColor: "#F1F5F9", color: "#334155", border: "1px solid #CBD5E1", cursor: "pointer", fontWeight: 600, fontSize: "14px" }}
          >
            Refresh Integrations
          </button>
        </div>
      </div>
    </div>
  );
}
