import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, Form, useActionData, useSubmit, useNavigation, useRouteError } from "react-router";
import {
  Page,
  Layout,
  Card,
  Text,
  BlockStack,
  InlineGrid,
  Badge,
  Banner,
  Button,
  Box,
  ProgressBar,
  TextField,
  Select,
  Checkbox,
  Tag,
  Divider,
  Modal,
} from "@shopify/polaris";
import { registerShop } from "../services/shop.server";
import { syncStoreCatalog } from "../services/catalog.server";
import { createSubscriptionCharge, ensureActiveSubscription, purchaseCreditPackage, CREDIT_PACKAGES } from "../services/billing.server";
import { getAvailableCredits } from "../services/credit-ledger.server";
import { SubscriptionService } from "../services/subscription.server";
import { PLAN_CONFIGS, canUseFeature } from "../lib/billing-plans";
import { getSaaSKPIMetrics, getInstalledStores, getStoreDetails, exportStoresCSV } from "../services/admin.server";
import { getDynamicAIProviders, validateAndSanitizeAIModel, type AIModelDefinition, type AIProviderDefinition } from "../services/ai-config.server";
import { createNotification } from "../services/notification.server";
import type { PlanTier } from "@prisma/client";
import prisma from "../db.server";
import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { FAIcon } from "../components/FAIcon";
import { parseWidgetSettings, serializeWidgetSettings } from "../services/widget-settings.server";
import { DEFAULT_WIDGET_TEXTS, type WidgetCustomTexts } from "../lib/widget-text-defaults";

import { resolveShopDomainFromRequest } from "../lib/security/tenant-context";

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

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const shopDomain = resolveShopDomainFromRequest(request);
  const url = new URL(request.url);
  const search = url.searchParams.get("search") || "";
  const planFilter = url.searchParams.get("planFilter") || "ALL";
  const statusFilter = url.searchParams.get("statusFilter") || "ALL";
  const sortBy = url.searchParams.get("sortBy") || "newest";
  const selectedStoreId = url.searchParams.get("storeId") || "";

  try {
    const shop = await registerShop({
      shopifyDomain: shopDomain,
      accessToken: "shpss_sample_token",
      scopes: "read_products,read_content",
    });

    const settings = await prisma.chatbotSettings.findUnique({
      where: { shopId: shop.id },
    });

    const subscription = await ensureActiveSubscription(shop.id);

    const conversationCount = await prisma.chatSession.count({
      where: { shopId: shop.id },
    }).catch(() => 0);

    const totalRevenue = await prisma.chatSession.aggregate({
      where: { shopId: shop.id, assistedSale: true },
      _sum: { revenueValue: true },
    }).catch(() => ({ _sum: { revenueValue: null } }));

    const productCount = await prisma.productCache.count({
      where: { shopId: shop.id },
    }).catch(() => 0);

    const articleCount = await prisma.articleCache.count({
      where: { shopId: shop.id },
    }).catch(() => 0);

    const storeArticles = await prisma.articleCache.findMany({
      where: { shopId: shop.id },
      orderBy: { publishedAt: "desc" },
      take: 10,
    }).catch(() => []);

    const knowledgeItems = await prisma.knowledgeBase.findMany({
      where: { shopId: shop.id },
      orderBy: { createdAt: "desc" },
    }).catch(() => []);

    const dynamicProviders = getDynamicAIProviders();
    const modelsByProvider: Record<string, AIModelDefinition[]> = {};
    dynamicProviders.forEach((p) => {
      modelsByProvider[p.id] = p.models;
    });

    const creditBalance = await getAvailableCredits(shop.id).catch(() => ({
      availableBalance: 0,
      totalAllocated: 0,
      totalUsed: 0,
      monthlyLimit: 0,
      monthlyUsed: 0,
      allocations: [],
    }));
    const billingSummary = await SubscriptionService.getBillingSummary(shop.id).catch(() => null);
    const { systemPromptText, widgetTexts } = parseWidgetSettings(settings);
    const isChatbotAdminDisabled = widgetTexts.adminDisabled === true;

    const { getPlansDictionary, getActivePlans } = await import("../services/plan-config.server");
    const { getActiveHelplines } = await import("../services/helpline-config.server");
    const plans = await getPlansDictionary().catch(() => PLAN_CONFIGS);
    const activePlansList = await getActivePlans().catch(() => []);
    const activeHelplines = await getActiveHelplines().catch(() => []);

    // Strict boolean resolution: enabled is true ONLY IF settings.enabled is explicitly true AND not adminDisabled
    const isEnabled = isChatbotAdminDisabled ? false : (settings?.enabled === true);

    return {
      shop: shop.shopifyDomain,
      storeId: shop.id,
      botName: widgetTexts.botName || settings?.botName || "ShopPilot AI Assistant",
      welcomeMessage: settings?.welcomeMessage || "Hi 👋 How can I help you find products, calculate shipping, or track orders today?",
      systemPrompt: systemPromptText,
      widgetTexts,
      primaryColor: settings?.primaryColor || "#4F46E5",
      secondaryColor: settings?.secondaryColor || "#4338CA",
      textColor: settings?.textColor || "#FFFFFF",
      botTextColor: settings?.botTextColor || "#1F2937",
      showPoweredBy: settings?.showPoweredBy ?? true,
      aiProvider: settings?.aiProvider || "openai",
      model: settings?.model || "gpt-4o-mini",
      temperature: settings?.temperature ?? 0.7,
      position: settings?.position || "bottom-right",
      isEnabled,
      isChatbotAdminDisabled,
      planTier: (subscription?.plan || "FREE") as PlanTier,
      monthlyLimit: subscription?.monthlyLimit || 100,
      currentUsage: subscription?.currentUsage || 0,
      creditBalance,
      billingSummary,
      creditPackages: CREDIT_PACKAGES,
      conversationCount,
      productCount,
      articleCount,
      articles: storeArticles.map((a) => ({
        id: a.id,
        shopifyArticleId: a.shopifyArticleId,
        blogHandle: a.blogHandle,
        blogTitle: a.blogTitle,
        title: a.title,
        handle: a.handle,
        summary: a.summary,
        url: a.url,
        publishedAt: a.publishedAt ? new Date(a.publishedAt).toLocaleDateString() : "",
      })),
      knowledgeCount: knowledgeItems.length,
      revenueGenerated: totalRevenue._sum?.revenueValue ? parseFloat(totalRevenue._sum.revenueValue.toString()) : 0.00,
      knowledgeItems: knowledgeItems.map((k) => ({
        id: k.id,
        title: k.title,
        content: k.content,
        sourceType: k.sourceType,
        enabled: k.enabled,
        createdAt: new Date(k.createdAt).toLocaleDateString(),
      })),
      dynamicProviders,
      modelsByProvider,
      plans,
      activePlansList,
      activeHelplines,
      adminKPIs: {
        totalStores: 1,
        activeStores: 1,
        uninstalledStores: 0,
        trialStores: 0,
        mrr: 0,
        arpu: 0,
        planBreakdown: { FREE: 1, STARTER: 0, GROWTH: 0, PRO: 0 },
      },
      adminStoresData: {
        stores: [],
        totalCount: 0,
        page: 1,
        totalPages: 1,
      },
      selectedStoreDetail: null,
      search,
      planFilter,
      statusFilter,
      sortBy,
    };
  } catch (e) {
    console.error("LOADER TRY BLOCK FAILED WITH ERROR in app._index.tsx:", e);
    let dbSettings: any = null;
    let dbSub: any = null;
    try {
      dbSettings = await prisma.chatbotSettings.findFirst({
        where: { shop: { shopifyDomain: shopDomain } },
      });
      dbSub = await prisma.subscription.findFirst({
        where: { shop: { shopifyDomain: shopDomain }, status: "ACTIVE" },
        orderBy: { createdAt: "desc" },
      });
    } catch (dbErr) {}

    const { systemPromptText, widgetTexts } = parseWidgetSettings(dbSettings);
    const isChatbotAdminDisabled = widgetTexts.adminDisabled === true;
    const fallbackIsEnabled = isChatbotAdminDisabled ? false : (dbSettings ? dbSettings.enabled === true : false);

    const dynamicProviders = getDynamicAIProviders();
    const modelsByProvider: Record<string, AIModelDefinition[]> = {};
    dynamicProviders.forEach((p) => {
      modelsByProvider[p.id] = p.models;
    });

    let fallbackPlans = PLAN_CONFIGS;
    let fallbackActivePlansList: any[] = [];
    let fallbackActiveHelplines: any[] = [];
    try {
      const { getPlansDictionary, getActivePlans } = await import("../services/plan-config.server");
      const { getActiveHelplines } = await import("../services/helpline-config.server");
      fallbackPlans = (await getPlansDictionary()) || PLAN_CONFIGS;
      fallbackActivePlansList = await getActivePlans();
      fallbackActiveHelplines = await getActiveHelplines();
    } catch (planErr) {
      fallbackActivePlansList = [];
      fallbackActiveHelplines = [];
    }

    if (!fallbackActivePlansList || fallbackActivePlansList.length === 0) {
      fallbackActivePlansList = Object.values(fallbackPlans || PLAN_CONFIGS)
        .filter((p: any) => p.isActive !== false)
        .map((cfg: any, idx: number) => ({
          id: `static_${cfg.name || cfg.planKey}`,
          planKey: cfg.name || cfg.planKey,
          displayName: cfg.displayName || cfg.name || cfg.planKey,
          price: cfg.price,
          billingType: cfg.billingType || (cfg.billingInterval === "ONE_TIME" ? "ONE_TIME" : "RECURRING"),
          billingInterval: cfg.billingInterval || "MONTHLY",
          aiUsageEnabled: cfg.aiUsageEnabled,
          aiMonthlyLimit: cfg.aiMonthlyLimit,
          monthlyLimit: cfg.monthlyLimit,
          description: cfg.description,
          features: cfg.features || [],
          isActive: true,
          sortOrder: idx + 1,
        }));
    }

    return {
      shop: shopDomain,
      storeId: dbSettings?.shopId || "local_dev_store",
      botName: widgetTexts.botName || dbSettings?.botName || "ShopPilot AI Assistant",
      welcomeMessage: dbSettings?.welcomeMessage || "Hi 👋 How can I help you find products, calculate shipping, or track orders today?",
      systemPrompt: systemPromptText || "",
      widgetTexts,
      primaryColor: dbSettings?.primaryColor || "#4F46E5",
      secondaryColor: dbSettings?.secondaryColor || "#4338CA",
      textColor: dbSettings?.textColor || "#FFFFFF",
      botTextColor: dbSettings?.botTextColor || "#1F2937",
      showPoweredBy: dbSettings?.showPoweredBy ?? true,
      aiProvider: dbSettings?.aiProvider || "openai",
      model: dbSettings?.model || "gpt-4o-mini",
      temperature: dbSettings?.temperature ?? 0.7,
      position: dbSettings?.position || "bottom-right",
      isEnabled: fallbackIsEnabled,
      isChatbotAdminDisabled,
      planTier: (dbSub?.plan || "FREE") as PlanTier,
      monthlyLimit: dbSub?.monthlyLimit || 100,
      currentUsage: dbSub?.currentUsage || 0,
      creditBalance: {
        availableBalance: 0,
        totalAllocated: 0,
        totalUsed: 0,
        monthlyLimit: 0,
        monthlyUsed: 0,
        allocations: [],
      },
      billingSummary: null,
      creditPackages: CREDIT_PACKAGES,
      conversationCount: 0,
      productCount: 0,
      articleCount: 0,
      articles: [],
      knowledgeCount: 0,
      revenueGenerated: 0.00,
      knowledgeItems: [],
      dynamicProviders,
      modelsByProvider,
      plans: fallbackPlans,
      activePlansList: fallbackActivePlansList,
      activeHelplines: fallbackActiveHelplines,
      adminKPIs: {
        totalStores: 1,
        activeStores: 1,
        uninstalledStores: 0,
        trialStores: 0,
        mrr: 0,
        arpu: 0,
        planBreakdown: { FREE: 1, STARTER: 0, GROWTH: 0, PRO: 0 },
      },
      adminStoresData: {
        stores: [],
        totalCount: 0,
        page: 1,
        totalPages: 1,
      },
      selectedStoreDetail: null,
      search: "",
      planFilter: "ALL",
      statusFilter: "ALL",
      sortBy: "newest",
    };
  }
};

export const action = async ({ request }: ActionFunctionArgs) => {
  try {
    const formData = await request.formData();
    const intent = String(formData.get("_intent") || "");
    const shopDomain = String(formData.get("shop") || resolveShopDomainFromRequest(request)).toLowerCase().trim();

    if (intent === "export_csv") {
      const csvContent = await exportStoresCSV();
      return new Response(csvContent, {
        status: 200,
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": 'attachment; filename="ConverseCart_Installed_Stores.csv"',
        },
      });
    }

    const shop = await registerShop({
      shopifyDomain: shopDomain,
      accessToken: "shpss_sample_token",
      scopes: "read_products,read_content",
    });

    if (intent === "save_ai_settings") {
      const botName = String(formData.get("botName") || "ShopPilot AI Assistant");
      const headerSubtext = String(formData.get("headerSubtext") || DEFAULT_WIDGET_TEXTS.headerSubtext);
      const headerInputPlaceholder = String(formData.get("headerInputPlaceholder") || DEFAULT_WIDGET_TEXTS.headerInputPlaceholder);
      const startHeading = String(formData.get("startHeading") || DEFAULT_WIDGET_TEXTS.startHeading);
      const startSubheading = String(formData.get("startSubheading") || DEFAULT_WIDGET_TEXTS.startSubheading);
      const starterPrompt1 = String(formData.get("starterPrompt1") || DEFAULT_WIDGET_TEXTS.starterPrompts[0]);
      const starterPrompt2 = String(formData.get("starterPrompt2") || DEFAULT_WIDGET_TEXTS.starterPrompts[1]);
      const starterPrompt3 = String(formData.get("starterPrompt3") || DEFAULT_WIDGET_TEXTS.starterPrompts[2]);
      const starterPrompt4 = String(formData.get("starterPrompt4") || DEFAULT_WIDGET_TEXTS.starterPrompts[3]);
      const starterPrompts = [starterPrompt1, starterPrompt2, starterPrompt3, starterPrompt4].filter((p) => p.trim().length > 0);
      const disclaimerText = String(formData.get("disclaimerText") || DEFAULT_WIDGET_TEXTS.disclaimerText);
      const disclaimerLinkText = String(formData.get("disclaimerLinkText") || DEFAULT_WIDGET_TEXTS.disclaimerLinkText);
      const disclaimerUrl = String(formData.get("disclaimerUrl") || DEFAULT_WIDGET_TEXTS.disclaimerUrl);
      const chatInputPlaceholder = String(formData.get("chatInputPlaceholder") || DEFAULT_WIDGET_TEXTS.chatInputPlaceholder);
      const footerTermsText = String(formData.get("footerTermsText") || DEFAULT_WIDGET_TEXTS.footerTermsText);
      const supportMenuItemText = String(formData.get("supportMenuItemText") || DEFAULT_WIDGET_TEXTS.supportMenuItemText);
      const clearMenuItemText = String(formData.get("clearMenuItemText") || DEFAULT_WIDGET_TEXTS.clearMenuItemText);
      const storeSupportEmail = String(formData.get("storeSupportEmail") || DEFAULT_WIDGET_TEXTS.storeSupportEmail || "");
      const storeSupportPhone = String(formData.get("storeSupportPhone") || DEFAULT_WIDGET_TEXTS.storeSupportPhone || "");
      const storeSupportHours = String(formData.get("storeSupportHours") || DEFAULT_WIDGET_TEXTS.storeSupportHours || "");
      const storeAddress = String(formData.get("storeAddress") || DEFAULT_WIDGET_TEXTS.storeAddress || "");
      const storeContactUrl = String(formData.get("storeContactUrl") || DEFAULT_WIDGET_TEXTS.storeContactUrl || "");
      const freeShippingThreshold = String(formData.get("freeShippingThreshold") || DEFAULT_WIDGET_TEXTS.freeShippingThreshold || "");
      const standardShippingFee = String(formData.get("standardShippingFee") || DEFAULT_WIDGET_TEXTS.standardShippingFee || "");
      const estimatedDeliveryDays = String(formData.get("estimatedDeliveryDays") || DEFAULT_WIDGET_TEXTS.estimatedDeliveryDays || "2 - 5 business days");
      const shippingPolicyUrl = String(formData.get("shippingPolicyUrl") || DEFAULT_WIDGET_TEXTS.shippingPolicyUrl || "/policies/shipping-policy");
      const rawSystemPrompt = String(formData.get("systemPrompt") || "");

      const activeSub = await prisma.subscription.findFirst({
        where: { shopId: shop.id, status: "ACTIVE" },
        orderBy: { createdAt: "desc" },
      });
      const planTier = activeSub?.plan || "FREE";
      const canRemoveBranding = planTier !== "FREE";
      const canUseCustomerAuth = canUseFeature(planTier, "shopify.customer_auth");
      const submittedCustomerAuth = formData.get("customerAuthEnabled") === "true";
      // Backend Security: Only Starter and Pro merchants can enable Customer Login & Registration
      const customerAuthEnabled = canUseCustomerAuth ? submittedCustomerAuth : false;
      const showCartSummary = formData.get("showCartSummary") === "true";

      const existingSettings = await prisma.chatbotSettings.findUnique({
        where: { shopId: shop.id },
      });
      const existingParsed = parseWidgetSettings(existingSettings);
      const isChatbotAdminDisabled = existingParsed.widgetTexts.adminDisabled === true;

      const serializedSystemPrompt = serializeWidgetSettings(rawSystemPrompt, {
        botName,
        headerSubtext,
        headerInputPlaceholder,
        startHeading,
        startSubheading,
        starterPrompts,
        disclaimerText,
        disclaimerLinkText,
        disclaimerUrl,
        chatInputPlaceholder,
        footerTermsText,
        supportMenuItemText,
        clearMenuItemText,
        customerAuthEnabled,
        showCartSummary,
        storeSupportEmail,
        storeSupportPhone,
        storeSupportHours,
        storeAddress,
        storeContactUrl,
        freeShippingThreshold,
        standardShippingFee,
        estimatedDeliveryDays,
        shippingPolicyUrl,
        adminDisabled: isChatbotAdminDisabled,
      });

      const primaryColor = String(formData.get("primaryColor") || "#4F46E5");
      const secondaryColor = String(formData.get("secondaryColor") || "#4338CA");
      const textColor = String(formData.get("textColor") || "#FFFFFF");
      const botTextColor = String(formData.get("botTextColor") || "#1F2937");
      const welcomeMessage = String(formData.get("welcomeMessage") || "Hi 👋 How can I help you find products or track orders today?");
      const submittedEnabled = formData.get("enabled") === "true";
      const enabled = isChatbotAdminDisabled ? false : submittedEnabled;
      const position = String(formData.get("position") || "bottom-right");
      const aiProvider = String(formData.get("aiProvider") || "openai");
      const submittedModel = String(formData.get("model") || "gpt-4o-mini");

      const submittedShowPoweredBy = formData.get("showPoweredBy") === "true";
      const showPoweredBy = canRemoveBranding ? submittedShowPoweredBy : true;

      const validated = validateAndSanitizeAIModel(aiProvider, submittedModel);
      const finalModel = validated.model;

      await prisma.chatbotSettings.upsert({
        where: { shopId: shop.id },
        update: {
          botName,
          primaryColor,
          secondaryColor,
          textColor,
          botTextColor,
          showPoweredBy,
          welcomeMessage,
          systemPrompt: serializedSystemPrompt,
          enabled,
          position,
          aiProvider,
          model: finalModel,
          ...(aiProvider === "openai" ? { openaiModel: finalModel } : {}),
          ...(aiProvider === "gemini" ? { geminiModel: finalModel } : {}),
        },
        create: {
          shopId: shop.id,
          botName,
          primaryColor,
          secondaryColor,
          textColor,
          botTextColor,
          showPoweredBy,
          welcomeMessage,
          systemPrompt: serializedSystemPrompt,
          enabled,
          position,
          aiProvider,
          model: finalModel,
          openaiModel: aiProvider === "openai" ? finalModel : "gpt-4o-mini",
          geminiModel: aiProvider === "gemini" ? finalModel : "gemini-1.5-flash",
        },
      });

      await createNotification({
        shopId: shop.id,
        type: "AI_CONFIG_UPDATED",
        title: "AI Configuration Updated",
        message: `Your AI provider (${aiProvider.toUpperCase()}) and model (${finalModel}) configuration were updated successfully.`,
        actionUrl: "/app",
      });

      return { 
        success: true, 
        intent: "save_ai_settings",
        message: `Successfully saved AI Engine (${aiProvider.toUpperCase()}: ${finalModel}) & Chatbot branding configuration!`,
        savedData: {
          enabled,
          primaryColor,
          secondaryColor,
          textColor,
          botTextColor,
          showPoweredBy,
          position,
          aiProvider,
          model: finalModel,
          botName,
          welcomeMessage,
          systemPrompt: rawSystemPrompt,
          widgetTexts: {
            botName,
            headerSubtext,
            headerInputPlaceholder,
            startHeading,
            startSubheading,
            starterPrompts,
            disclaimerText,
            disclaimerLinkText,
            disclaimerUrl,
            chatInputPlaceholder,
            footerTermsText,
            supportMenuItemText,
            clearMenuItemText,
            customerAuthEnabled,
            showCartSummary,
            storeSupportEmail,
            storeSupportPhone,
            storeSupportHours,
            storeAddress,
            storeContactUrl,
            freeShippingThreshold,
            standardShippingFee,
            estimatedDeliveryDays,
            shippingPolicyUrl,
            adminDisabled: isChatbotAdminDisabled,
          },
        },
      };
    }

    if (intent === "add_knowledge") {
      const title = String(formData.get("title") || "").trim();
      const content = String(formData.get("content") || "").trim();
      const sourceType = String(formData.get("sourceType") || "faq");

      if (!title || !content) {
        return { success: false, error: "Please enter both Title and Content for the Knowledge Base entry." };
      }

      await prisma.knowledgeBase.create({
        data: { shopId: shop.id, title, content, sourceType, enabled: true },
      });

      return { success: true, message: `Added new Knowledge Base entry: "${title}"!` };
    }

    if (intent === "update_knowledge") {
      const kId = String(formData.get("kId") || "");
      const title = String(formData.get("title") || "").trim();
      const content = String(formData.get("content") || "").trim();
      const sourceType = String(formData.get("sourceType") || "faq");

      if (!kId || !title || !content) {
        return { success: false, error: "Please provide valid Title and Content for updating." };
      }

      await prisma.knowledgeBase.update({
        where: { id: kId },
        data: { title, content, sourceType },
      });

      return { success: true, message: `Updated Knowledge Base item: "${title}"!` };
    }

    if (intent === "toggle_knowledge") {
      const kId = String(formData.get("kId") || "");
      const currentEnabled = formData.get("enabled") === "true";
      await prisma.knowledgeBase.update({
        where: { id: kId },
        data: { enabled: !currentEnabled },
      });
      return { success: true, message: "Knowledge Base item status updated!" };
    }

    if (intent === "delete_knowledge") {
      const kId = String(formData.get("kId") || "");
      await prisma.knowledgeBase.delete({ where: { id: kId } });
      return { success: true, message: "Knowledge Base entry deleted." };
    }

    if (intent === "sync_catalog") {
      await syncStoreCatalog(shopDomain);
      return { success: true, message: `Triggered live catalog & blog sync for store ${shopDomain}!` };
    }

    if (intent === "sync_blogs" || intent === "sync_articles") {
      const { syncStoreArticles } = await import("../services/article.server");
      const res = await syncStoreArticles(shopDomain);
      return { success: true, message: `Successfully synchronized ${res.syncedCount} store blog posts & articles!` };
    }

    if (intent === "change_plan") {
      const plan = formData.get("plan") as PlanTier;
      const cardName = String(formData.get("cardName") || "").trim();
      const cardNumber = String(formData.get("cardNumber") || "").trim();
      const cardExpiry = String(formData.get("cardExpiry") || "").trim();
      const cardCvc = String(formData.get("cardCvc") || "").trim();
      const paymentMethod = String(formData.get("paymentMethod") || "card").trim();
      const paymentAmountStr = formData.get("paymentAmount");
      const paymentAmount = paymentAmountStr !== null ? parseFloat(String(paymentAmountStr)) : undefined;

      if (plan) {
        const result = await createSubscriptionCharge({
          shopDomain,
          plan,
          paymentDetails: {
            cardName,
            cardNumber,
            cardExpiry,
            cardCvc,
            paymentMethod,
            paymentAmount,
          },
        });

        if (!result.success) {
          return { success: false, error: result.error || "Payment verification failed. Please verify your card details." };
        }

        return {
          success: true,
          message: result.message || `Payment verified and subscription activated for ${plan} plan!`,
          confirmationUrl: result.confirmationUrl,
        };
      }
    }

    if (intent === "purchase_credits") {
      const packageId = String(formData.get("packageId") || "PKG_1000");
      const cardName = String(formData.get("cardName") || "").trim();
      const cardNumber = String(formData.get("cardNumber") || "").trim();
      const cardExpiry = String(formData.get("cardExpiry") || "").trim();
      const cardCvc = String(formData.get("cardCvc") || "").trim();

      const result = await purchaseCreditPackage({
        shopDomain,
        packageId,
        paymentDetails: { cardName, cardNumber, cardExpiry, cardCvc },
      });

      if (!result.success) {
        return { success: false, error: result.error || "Credit package payment verification failed." };
      }

      return {
        success: true,
        message: result.message,
      };
    }

    return null;
  } catch (error: any) {
    console.error("[Action Handler Error in app._index.tsx]:", error);
    return {
      success: false,
      error: error?.message || "An unexpected error occurred while processing your request. Please try again.",
    };
  }
};

export default function UnifiedSaaSDashboard() {
  const loaderData = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();

  const { dynamicProviders, modelsByProvider } = loaderData;

  const availablePlans = (loaderData.activePlansList && Array.isArray(loaderData.activePlansList) && loaderData.activePlansList.length > 0)
    ? loaderData.activePlansList.filter((p: any) => p.isActive === true)
    : Object.values(loaderData.plans || PLAN_CONFIGS)
        .filter((p: any) => (p as any).isActive !== false)
        .map((cfg: any, idx: number) => ({
          id: `static_${cfg.name || cfg.planKey}`,
          planKey: cfg.name || cfg.planKey,
          displayName: cfg.displayName || cfg.name || cfg.planKey,
          price: cfg.price,
          billingType: cfg.billingType || (cfg.billingInterval === "ONE_TIME" ? "ONE_TIME" : "RECURRING"),
          billingInterval: cfg.billingInterval || "MONTHLY",
          aiUsageEnabled: cfg.aiUsageEnabled,
          aiMonthlyLimit: cfg.aiMonthlyLimit,
          monthlyLimit: cfg.monthlyLimit,
          description: cfg.description,
          features: cfg.features || [],
          isActive: true,
          sortOrder: idx + 1,
        }));

  const currentPlanConfig = availablePlans.find((p: any) => (p.planKey || p.name) === loaderData.planTier)
    || (loaderData.plans && loaderData.plans[loaderData.planTier])
    || (PLAN_CONFIGS as any)[loaderData.planTier]
    || PLAN_CONFIGS.FREE;

  const canRemoveBranding = loaderData.planTier !== "FREE";
  const canUseAI = canUseFeature(loaderData.planTier, "openai");
  const canUseCustomerAuth = canUseFeature(loaderData.planTier, "shopify.customer_auth");
  const [botName, setBotName] = useState(loaderData.botName);
  const [primaryColor, setPrimaryColor] = useState(loaderData.primaryColor);
  const [secondaryColor, setSecondaryColor] = useState(loaderData.secondaryColor || "#4338CA");
  const [textColor, setTextColor] = useState(loaderData.textColor || "#FFFFFF");
  const [botTextColor, setBotTextColor] = useState(loaderData.botTextColor || "#1F2937");
  const [showPoweredBy, setShowPoweredBy] = useState<boolean>(loaderData.showPoweredBy ?? true);
  const [welcomeMessage, setWelcomeMessage] = useState(loaderData.welcomeMessage);
  const [systemPrompt, setSystemPrompt] = useState(loaderData.systemPrompt);
  const [enabled, setEnabled] = useState(loaderData.isEnabled);
  const [position, setPosition] = useState(loaderData.position || "bottom-right");
  const [aiProvider, setAiProvider] = useState(loaderData.aiProvider);
  const [model, setModel] = useState(loaderData.model);

  // Storefront Widget Customizable Texts State
  const initialTexts = loaderData.widgetTexts || DEFAULT_WIDGET_TEXTS;
  const [headerSubtext, setHeaderSubtext] = useState(initialTexts.headerSubtext || DEFAULT_WIDGET_TEXTS.headerSubtext);
  const [headerInputPlaceholder, setHeaderInputPlaceholder] = useState(initialTexts.headerInputPlaceholder || DEFAULT_WIDGET_TEXTS.headerInputPlaceholder);
  const [startHeading, setStartHeading] = useState(initialTexts.startHeading || DEFAULT_WIDGET_TEXTS.startHeading);
  const [startSubheading, setStartSubheading] = useState(initialTexts.startSubheading || DEFAULT_WIDGET_TEXTS.startSubheading);
  const [starterPrompt1, setStarterPrompt1] = useState(initialTexts.starterPrompts?.[0] || DEFAULT_WIDGET_TEXTS.starterPrompts[0]);
  const [starterPrompt2, setStarterPrompt2] = useState(initialTexts.starterPrompts?.[1] || DEFAULT_WIDGET_TEXTS.starterPrompts[1]);
  const [starterPrompt3, setStarterPrompt3] = useState(initialTexts.starterPrompts?.[2] || DEFAULT_WIDGET_TEXTS.starterPrompts[2]);
  const [starterPrompt4, setStarterPrompt4] = useState(initialTexts.starterPrompts?.[3] || DEFAULT_WIDGET_TEXTS.starterPrompts[3]);
  const [disclaimerText, setDisclaimerText] = useState(initialTexts.disclaimerText || DEFAULT_WIDGET_TEXTS.disclaimerText);
  const [disclaimerLinkText, setDisclaimerLinkText] = useState(initialTexts.disclaimerLinkText || DEFAULT_WIDGET_TEXTS.disclaimerLinkText);
  const [disclaimerUrl, setDisclaimerUrl] = useState(initialTexts.disclaimerUrl || DEFAULT_WIDGET_TEXTS.disclaimerUrl);
  const [chatInputPlaceholder, setChatInputPlaceholder] = useState(initialTexts.chatInputPlaceholder || DEFAULT_WIDGET_TEXTS.chatInputPlaceholder);
  const [footerTermsText, setFooterTermsText] = useState(initialTexts.footerTermsText || DEFAULT_WIDGET_TEXTS.footerTermsText);
  const [supportMenuItemText, setSupportMenuItemText] = useState(initialTexts.supportMenuItemText || DEFAULT_WIDGET_TEXTS.supportMenuItemText);
  const [clearMenuItemText, setClearMenuItemText] = useState(initialTexts.clearMenuItemText || DEFAULT_WIDGET_TEXTS.clearMenuItemText);
  const [customerAuthEnabled, setCustomerAuthEnabled] = useState(initialTexts.customerAuthEnabled === true);
  const [showCartSummary, setShowCartSummary] = useState<boolean>(initialTexts.showCartSummary !== false);
  const [storeSupportEmail, setStoreSupportEmail] = useState(initialTexts.storeSupportEmail || DEFAULT_WIDGET_TEXTS.storeSupportEmail || "");
  const [storeSupportPhone, setStoreSupportPhone] = useState(initialTexts.storeSupportPhone || DEFAULT_WIDGET_TEXTS.storeSupportPhone || "");
  const [storeSupportHours, setStoreSupportHours] = useState(initialTexts.storeSupportHours || DEFAULT_WIDGET_TEXTS.storeSupportHours || "");
  const [storeAddress, setStoreAddress] = useState(initialTexts.storeAddress || DEFAULT_WIDGET_TEXTS.storeAddress || "");
  const [storeContactUrl, setStoreContactUrl] = useState(initialTexts.storeContactUrl || DEFAULT_WIDGET_TEXTS.storeContactUrl || "");
  const [freeShippingThreshold, setFreeShippingThreshold] = useState(initialTexts.freeShippingThreshold || DEFAULT_WIDGET_TEXTS.freeShippingThreshold || "");
  const [standardShippingFee, setStandardShippingFee] = useState(initialTexts.standardShippingFee || DEFAULT_WIDGET_TEXTS.standardShippingFee || "");
  const [estimatedDeliveryDays, setEstimatedDeliveryDays] = useState(initialTexts.estimatedDeliveryDays || DEFAULT_WIDGET_TEXTS.estimatedDeliveryDays || "2 - 5 business days");
  const [shippingPolicyUrl, setShippingPolicyUrl] = useState(initialTexts.shippingPolicyUrl || DEFAULT_WIDGET_TEXTS.shippingPolicyUrl || "/policies/shipping-policy");

  // Live Preview Mode Switcher State ("welcome" = Getting Started screen, "active" = Active Chat conversation)
  const [previewTab, setPreviewTab] = useState<"welcome" | "active">("welcome");

  // Sync state whenever loaderData or actionData updates (after successful save, revalidation, or load)
  useEffect(() => {
    if (actionData?.intent === "save_ai_settings" && (actionData as any)?.savedData) {
      const data = (actionData as any).savedData;
      setAiProvider(data.aiProvider);
      setModel(data.model);
      setBotName(data.botName);
      setPrimaryColor(data.primaryColor || "#4F46E5");
      setSecondaryColor(data.secondaryColor || "#4338CA");
      setTextColor(data.textColor || "#FFFFFF");
      setBotTextColor(data.botTextColor || "#1F2937");
      setShowPoweredBy(data.showPoweredBy ?? true);
      setWelcomeMessage(data.welcomeMessage);
      setSystemPrompt(data.systemPrompt);
      setEnabled(data.enabled);
      setPosition(data.position || "bottom-right");

      const txts = data.widgetTexts || DEFAULT_WIDGET_TEXTS;
      setHeaderSubtext(txts.headerSubtext || DEFAULT_WIDGET_TEXTS.headerSubtext);
      setHeaderInputPlaceholder(txts.headerInputPlaceholder || DEFAULT_WIDGET_TEXTS.headerInputPlaceholder);
      setStartHeading(txts.startHeading || DEFAULT_WIDGET_TEXTS.startHeading);
      setStartSubheading(txts.startSubheading || DEFAULT_WIDGET_TEXTS.startSubheading);
      setStarterPrompt1(txts.starterPrompts?.[0] || DEFAULT_WIDGET_TEXTS.starterPrompts[0]);
      setStarterPrompt2(txts.starterPrompts?.[1] || DEFAULT_WIDGET_TEXTS.starterPrompts[1]);
      setStarterPrompt3(txts.starterPrompts?.[2] || DEFAULT_WIDGET_TEXTS.starterPrompts[2]);
      setStarterPrompt4(txts.starterPrompts?.[3] || DEFAULT_WIDGET_TEXTS.starterPrompts[3]);
      setDisclaimerText(txts.disclaimerText || DEFAULT_WIDGET_TEXTS.disclaimerText);
      setDisclaimerLinkText(txts.disclaimerLinkText || DEFAULT_WIDGET_TEXTS.disclaimerLinkText);
      setDisclaimerUrl(txts.disclaimerUrl || DEFAULT_WIDGET_TEXTS.disclaimerUrl);
      setChatInputPlaceholder(txts.chatInputPlaceholder || DEFAULT_WIDGET_TEXTS.chatInputPlaceholder);
      setFooterTermsText(txts.footerTermsText || DEFAULT_WIDGET_TEXTS.footerTermsText);
      setSupportMenuItemText(txts.supportMenuItemText || DEFAULT_WIDGET_TEXTS.supportMenuItemText);
      setClearMenuItemText(txts.clearMenuItemText || DEFAULT_WIDGET_TEXTS.clearMenuItemText);
      setCustomerAuthEnabled(txts.customerAuthEnabled === true);
      setShowCartSummary(txts.showCartSummary !== false);
      setStoreSupportEmail(txts.storeSupportEmail || DEFAULT_WIDGET_TEXTS.storeSupportEmail || "");
      setStoreSupportPhone(txts.storeSupportPhone || DEFAULT_WIDGET_TEXTS.storeSupportPhone || "");
      setStoreSupportHours(txts.storeSupportHours || DEFAULT_WIDGET_TEXTS.storeSupportHours || "");
      setStoreAddress(txts.storeAddress || DEFAULT_WIDGET_TEXTS.storeAddress || "");
      setStoreContactUrl(txts.storeContactUrl || DEFAULT_WIDGET_TEXTS.storeContactUrl || "");
      setFreeShippingThreshold(txts.freeShippingThreshold || DEFAULT_WIDGET_TEXTS.freeShippingThreshold || "");
      setStandardShippingFee(txts.standardShippingFee || DEFAULT_WIDGET_TEXTS.standardShippingFee || "");
      setEstimatedDeliveryDays(txts.estimatedDeliveryDays || DEFAULT_WIDGET_TEXTS.estimatedDeliveryDays || "2 - 5 business days");
      setShippingPolicyUrl(txts.shippingPolicyUrl || DEFAULT_WIDGET_TEXTS.shippingPolicyUrl || "/policies/shipping-policy");
    } else if (loaderData) {
      setAiProvider(loaderData.aiProvider);
      setModel(loaderData.model);
      setBotName(loaderData.botName);
      setPrimaryColor(loaderData.primaryColor || "#4F46E5");
      setSecondaryColor(loaderData.secondaryColor || "#4338CA");
      setTextColor(loaderData.textColor || "#FFFFFF");
      setBotTextColor(loaderData.botTextColor || "#1F2937");
      setShowPoweredBy(loaderData.showPoweredBy ?? true);
      setWelcomeMessage(loaderData.welcomeMessage);
      setSystemPrompt(loaderData.systemPrompt);
      setEnabled(loaderData.isEnabled);
      setPosition(loaderData.position || "bottom-right");

      const txts = loaderData.widgetTexts || DEFAULT_WIDGET_TEXTS;
      setHeaderSubtext(txts.headerSubtext || DEFAULT_WIDGET_TEXTS.headerSubtext);
      setHeaderInputPlaceholder(txts.headerInputPlaceholder || DEFAULT_WIDGET_TEXTS.headerInputPlaceholder);
      setStartHeading(txts.startHeading || DEFAULT_WIDGET_TEXTS.startHeading);
      setStartSubheading(txts.startSubheading || DEFAULT_WIDGET_TEXTS.startSubheading);
      setStarterPrompt1(txts.starterPrompts?.[0] || DEFAULT_WIDGET_TEXTS.starterPrompts[0]);
      setStarterPrompt2(txts.starterPrompts?.[1] || DEFAULT_WIDGET_TEXTS.starterPrompts[1]);
      setStarterPrompt3(txts.starterPrompts?.[2] || DEFAULT_WIDGET_TEXTS.starterPrompts[2]);
      setStarterPrompt4(txts.starterPrompts?.[3] || DEFAULT_WIDGET_TEXTS.starterPrompts[3]);
      setDisclaimerText(txts.disclaimerText || DEFAULT_WIDGET_TEXTS.disclaimerText);
      setDisclaimerLinkText(txts.disclaimerLinkText || DEFAULT_WIDGET_TEXTS.disclaimerLinkText);
      setDisclaimerUrl(txts.disclaimerUrl || DEFAULT_WIDGET_TEXTS.disclaimerUrl);
      setChatInputPlaceholder(txts.chatInputPlaceholder || DEFAULT_WIDGET_TEXTS.chatInputPlaceholder);
      setFooterTermsText(txts.footerTermsText || DEFAULT_WIDGET_TEXTS.footerTermsText);
      setSupportMenuItemText(txts.supportMenuItemText || DEFAULT_WIDGET_TEXTS.supportMenuItemText);
      setClearMenuItemText(txts.clearMenuItemText || DEFAULT_WIDGET_TEXTS.clearMenuItemText);
      setCustomerAuthEnabled(txts.customerAuthEnabled === true);
      setShowCartSummary(txts.showCartSummary !== false);
      setStoreSupportEmail(txts.storeSupportEmail || DEFAULT_WIDGET_TEXTS.storeSupportEmail || "");
      setStoreSupportPhone(txts.storeSupportPhone || DEFAULT_WIDGET_TEXTS.storeSupportPhone || "");
      setStoreSupportHours(txts.storeSupportHours || DEFAULT_WIDGET_TEXTS.storeSupportHours || "");
      setStoreAddress(txts.storeAddress || DEFAULT_WIDGET_TEXTS.storeAddress || "");
      setStoreContactUrl(txts.storeContactUrl || DEFAULT_WIDGET_TEXTS.storeContactUrl || "");
      setFreeShippingThreshold(txts.freeShippingThreshold || DEFAULT_WIDGET_TEXTS.freeShippingThreshold || "");
      setStandardShippingFee(txts.standardShippingFee || DEFAULT_WIDGET_TEXTS.standardShippingFee || "");
      setEstimatedDeliveryDays(txts.estimatedDeliveryDays || DEFAULT_WIDGET_TEXTS.estimatedDeliveryDays || "2 - 5 business days");
      setShippingPolicyUrl(txts.shippingPolicyUrl || DEFAULT_WIDGET_TEXTS.shippingPolicyUrl || "/policies/shipping-policy");
    }
  }, [loaderData, actionData]);

  // Knowledge Base Form States
  const [kTitle, setKTitle] = useState("");
  const [kContent, setKContent] = useState("");
  const [kType, setKType] = useState("faq");

  // Knowledge Base Editing State
  const [editItem, setEditItem] = useState<{ id: string; title: string; content: string; sourceType: string } | null>(null);

  // Subscription Plan & Checkout Modal States
  const [showPlansModal, setShowPlansModal] = useState(false);
  const [selectedCheckoutPlan, setSelectedCheckoutPlan] = useState<PlanTier | null>(null);
  const [selectedHistorySub, setSelectedHistorySub] = useState<any | null>(null);
  const [selectedPaymentReceipt, setSelectedPaymentReceipt] = useState<any | null>(null);
  const [paymentMethod, setPaymentMethod] = useState("shopify");

  // Payment Form States
  const [cardName, setCardName] = useState("");
  const [cardNumber, setCardNumber] = useState("");
  const [cardExpiry, setCardExpiry] = useState("");
  const [cardCvc, setCardCvc] = useState("");

  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => {
    setIsMounted(true);
  }, []);

  // Dynamic Provider Options
  const providerOptions = dynamicProviders.map((p) => ({
    label: `${p.name} (${p.badge})`,
    value: p.id,
  }));

  // Dynamic Models for currently selected Provider
  const currentModels = modelsByProvider[aiProvider] || [];
  const modelOptions = currentModels.map((m) => ({
    label: m.label,
    value: m.value,
  }));

  const selectedProviderDetail = dynamicProviders.find((p) => p.id === aiProvider) || dynamicProviders[0];
  const selectedModelDetail = currentModels.find((m) => m.value === model) || currentModels[0] || {
    label: model,
    value: model,
    description: "Custom AI engine model.",
    badge: "Active",
    speedRating: "Standard",
  };

  const submit = useSubmit();
  const navigation = useNavigation();
  const isSaving = navigation.state === "submitting" || navigation.state === "loading";

  const handleProviderChange = (newProvider: string) => {
    setAiProvider(newProvider);
    const availableModels = modelsByProvider[newProvider] || [];
    if (availableModels.length > 0) {
      const rec = availableModels.find((m) => m.recommended) || availableModels[0];
      setModel(rec.value);
    }
  };

  const handleModelChange = (newModel: string) => {
    setModel(newModel);
  };

  const handleColorChange = (newColor: string) => {
    setPrimaryColor(newColor);
  };

  const handleSecondaryColorChange = (newColor: string) => {
    setSecondaryColor(newColor);
  };

  const handleTextColorChange = (newColor: string) => {
    setTextColor(newColor);
  };

  const handleBotTextColorChange = (newColor: string) => {
    setBotTextColor(newColor);
  };

  const handleShowPoweredByChange = (val: boolean) => {
    if (!canRemoveBranding) return;
    setShowPoweredBy(val);
  };

  const isUnlimitedPlan = loaderData.monthlyLimit >= 99999 || loaderData.planTier === "PRO";
  const usagePercentage = isUnlimitedPlan
    ? 5
    : Math.min(100, Math.round((loaderData.currentUsage / Math.max(1, loaderData.monthlyLimit)) * 100));

  const initialWidgetTexts = loaderData.widgetTexts || DEFAULT_WIDGET_TEXTS;
  const isDirty =
    botName !== loaderData.botName ||
    primaryColor !== loaderData.primaryColor ||
    secondaryColor !== (loaderData.secondaryColor || "#4338CA") ||
    textColor !== (loaderData.textColor || "#FFFFFF") ||
    botTextColor !== (loaderData.botTextColor || "#1F2937") ||
    showPoweredBy !== (loaderData.showPoweredBy ?? true) ||
    welcomeMessage !== loaderData.welcomeMessage ||
    systemPrompt !== loaderData.systemPrompt ||
    enabled !== loaderData.isEnabled ||
    position !== (loaderData.position || "bottom-right") ||
    aiProvider !== loaderData.aiProvider ||
    model !== loaderData.model ||
    headerSubtext !== (initialWidgetTexts.headerSubtext || DEFAULT_WIDGET_TEXTS.headerSubtext) ||
    headerInputPlaceholder !== (initialWidgetTexts.headerInputPlaceholder || DEFAULT_WIDGET_TEXTS.headerInputPlaceholder) ||
    startHeading !== (initialWidgetTexts.startHeading || DEFAULT_WIDGET_TEXTS.startHeading) ||
    startSubheading !== (initialWidgetTexts.startSubheading || DEFAULT_WIDGET_TEXTS.startSubheading) ||
    starterPrompt1 !== (initialWidgetTexts.starterPrompts?.[0] || DEFAULT_WIDGET_TEXTS.starterPrompts[0]) ||
    starterPrompt2 !== (initialWidgetTexts.starterPrompts?.[1] || DEFAULT_WIDGET_TEXTS.starterPrompts[1]) ||
    starterPrompt3 !== (initialWidgetTexts.starterPrompts?.[2] || DEFAULT_WIDGET_TEXTS.starterPrompts[2]) ||
    starterPrompt4 !== (initialWidgetTexts.starterPrompts?.[3] || DEFAULT_WIDGET_TEXTS.starterPrompts[3]) ||
    disclaimerText !== (initialWidgetTexts.disclaimerText || DEFAULT_WIDGET_TEXTS.disclaimerText) ||
    disclaimerLinkText !== (initialWidgetTexts.disclaimerLinkText || DEFAULT_WIDGET_TEXTS.disclaimerLinkText) ||
    disclaimerUrl !== (initialWidgetTexts.disclaimerUrl || DEFAULT_WIDGET_TEXTS.disclaimerUrl) ||
    chatInputPlaceholder !== (initialWidgetTexts.chatInputPlaceholder || DEFAULT_WIDGET_TEXTS.chatInputPlaceholder) ||
    footerTermsText !== (initialWidgetTexts.footerTermsText || DEFAULT_WIDGET_TEXTS.footerTermsText) ||
    supportMenuItemText !== (initialWidgetTexts.supportMenuItemText || DEFAULT_WIDGET_TEXTS.supportMenuItemText) ||
    clearMenuItemText !== (initialWidgetTexts.clearMenuItemText || DEFAULT_WIDGET_TEXTS.clearMenuItemText) ||
    customerAuthEnabled !== (initialWidgetTexts.customerAuthEnabled === true) ||
    showCartSummary !== (initialWidgetTexts.showCartSummary !== false) ||
    storeSupportEmail !== (initialWidgetTexts.storeSupportEmail || DEFAULT_WIDGET_TEXTS.storeSupportEmail || "") ||
    storeSupportPhone !== (initialWidgetTexts.storeSupportPhone || DEFAULT_WIDGET_TEXTS.storeSupportPhone || "") ||
    storeSupportHours !== (initialWidgetTexts.storeSupportHours || DEFAULT_WIDGET_TEXTS.storeSupportHours || "") ||
    storeAddress !== (initialWidgetTexts.storeAddress || DEFAULT_WIDGET_TEXTS.storeAddress || "") ||
    storeContactUrl !== (initialWidgetTexts.storeContactUrl || DEFAULT_WIDGET_TEXTS.storeContactUrl || "") ||
    freeShippingThreshold !== (initialWidgetTexts.freeShippingThreshold || DEFAULT_WIDGET_TEXTS.freeShippingThreshold || "") ||
    standardShippingFee !== (initialWidgetTexts.standardShippingFee || DEFAULT_WIDGET_TEXTS.standardShippingFee || "") ||
    estimatedDeliveryDays !== (initialWidgetTexts.estimatedDeliveryDays || DEFAULT_WIDGET_TEXTS.estimatedDeliveryDays || "2 - 5 business days") ||
    shippingPolicyUrl !== (initialWidgetTexts.shippingPolicyUrl || DEFAULT_WIDGET_TEXTS.shippingPolicyUrl || "/policies/shipping-policy");

  return (
    <div className="cc-dashboard-wrapper">
      {/* HEADER SECTION */}
      <header className="cc-header">
        <div className="cc-header-brand">
          <div className="cc-logo-badge">
            <FAIcon name="robot" />
          </div>
          <div className="cc-header-titles">
            <h1>ShopPilot AI — Control Panel</h1>
            <p>Configure AI engine, dynamic knowledge base, branding, and billing limits.</p>
          </div>
        </div>
      </header>

      {/* NOTIFICATIONS / ACTION FEEDBACK BANNERS */}
      {actionData?.message && (
        <div style={{ marginBottom: "20px" }}>
          <Banner title="Success" tone="success">
            <p>{actionData.message}</p>
          </Banner>
        </div>
      )}

      {actionData?.error && (
        <div style={{ marginBottom: "20px" }}>
          <Banner title="Error" tone="critical">
            <p>{actionData.error}</p>
          </Banner>
        </div>
      )}

      {/* 2-COLUMN DASHBOARD GRID */}
      <div className="cc-grid">
        {/* MAIN 70% COLUMN */}
        <div>
          {/* CURRENT ACTIVE PLAN HIGHLIGHT CARD */}
          {/* <div className="cc-card" style={{ border: "2px solid #4f46e5", background: "linear-gradient(180deg, #f8fafc 0%, #ffffff 100%)", marginBottom: "20px" }}>
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon" style={{ background: "#4f46e5", color: "#ffffff" }}>
                  <FAIcon name="crown" />
                </div>
                <span style={{ fontSize: "16px", fontWeight: 700 }}>Current Active Plan</span>
              </div>
              <Badge tone="success">ACTIVE</Badge>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px", marginBottom: "16px" }}>
              <div>
                <div style={{ fontSize: "24px", fontWeight: 800, color: "#0f172a" }}>
                  {loaderData.billingSummary?.activeSubscription?.plan || loaderData.planTier} PLAN
                </div>
                <div style={{ fontSize: "18px", fontWeight: 700, color: "#4f46e5", marginTop: "2px" }}>
                  ${loaderData.billingSummary?.activeSubscription?.price || currentPlanConfig.price} / month
                </div>
                <div style={{ fontSize: "12px", color: "#64748b", marginTop: "6px" }}>
                  Started: {new Date(loaderData.billingSummary?.activeSubscription?.startedAt || Date.now()).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </div>
                <div style={{ fontSize: "12px", color: "#64748b" }}>
                  Next renewal: <strong>{new Date(loaderData.billingSummary?.activeSubscription?.currentPeriodEnd || Date.now()).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</strong>
                </div>
              </div>

              <div style={{ background: "#f1f5f9", padding: "14px", borderRadius: "10px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", fontWeight: 600, color: "#334155" }}>
                  <span>Monthly Usage:</span>
                  <span>{loaderData.billingSummary?.activeSubscription?.currentUsage || loaderData.currentUsage} / {loaderData.billingSummary?.activeSubscription?.monthlyLimit || loaderData.monthlyLimit}</span>
                </div>
                <div className="cc-progress-track" style={{ margin: "6px 0 10px 0" }}>
                  <div className="cc-progress-fill" style={{ width: `${usagePercentage}%`, backgroundColor: "#4f46e5" }} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", fontWeight: 600, color: "#334155" }}>
                  <span>Available Credits:</span>
                  <strong style={{ color: "#059669" }}>{(loaderData.billingSummary?.creditBalance?.availableBalance || 1600).toLocaleString()} Credits</strong>
                </div>
              </div>
            </div>

            <div style={{ display: "flex", gap: "10px" }}>
              <button type="button" className="cc-btn cc-btn-primary" onClick={() => setShowPlansModal(true)}>
                <FAIcon name="rocket" /> Manage Plan
              </button>
              <button type="button" className="cc-btn cc-btn-secondary" onClick={() => setShowBuyCreditsModal(true)}>
                <FAIcon name="bolt" /> Buy Credits
              </button>
            </div>
          </div> */}

          <Form method="post">
            <input type="hidden" name="shop" value={loaderData.shop} />
            <input type="hidden" name="_intent" value="save_ai_settings" />

            {/* AI ENGINE & MODEL MANAGEMENT CARD - EXCLUSIVE TO PRO TIER */}
            {canUseAI ? (
              <div className="cc-card">
                <div className="cc-card-header">
                  <div className="cc-card-title">
                    <div className="cc-card-icon">
                      <FAIcon name={selectedProviderDetail.iconName || "microchip"} />
                    </div>
                    <span>AI Engine & Model Management</span>
                  </div>
                  <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
                    <Badge tone="success">PRO PLAN EXCLUSIVE</Badge>
                    <Badge tone={aiProvider === "gemini" ? "attention" : aiProvider === "local" ? "warning" : "info"}>
                      {selectedProviderDetail.badge}
                    </Badge>
                  </div>
                </div>

                <p className="cc-body-text" style={{ marginTop: 0, marginBottom: "20px" }}>
                  Select your store's preferred AI provider (OpenAI, Google Gemini, or Local Engine). Models update dynamically based on the selected provider. (Exclusive to Pro Plan subscribers).
                </p>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "20px" }}>
                  <div>
                    <label className="cc-label">AI Engine Provider</label>
                    <select
                      name="aiProvider"
                      className="cc-select"
                      value={aiProvider}
                      onChange={(e) => handleProviderChange(e.target.value)}
                    >
                      {providerOptions.map((opt) => (
                        <option key={opt.value} value={opt.value}>
                          {opt.label}
                        </option>
                      ))}
                    </select>
                    <div className="cc-subtext">Currently selected: {selectedProviderDetail.name}</div>
                  </div>

                  <div>
                    <label className="cc-label">AI Model Selection</label>
                    <select
                      name="model"
                      className="cc-select"
                      value={model}
                      onChange={(e) => handleModelChange(e.target.value)}
                    >
                      {modelOptions.map((opt) => (
                        <option key={opt.value} value={opt.value}>
                          {opt.label}
                        </option>
                      ))}
                    </select>
                    <div className="cc-subtext">Available models dynamically loaded for {selectedProviderDetail.name}</div>
                  </div>
                </div>

                {/* DYNAMIC SELECTED MODEL BOX */}
                <div className="cc-model-highlight-box">
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                      <FAIcon name="microchip" style={{ color: "#008060" }} />
                      <span style={{ fontWeight: 600, fontSize: "14px", color: "#303030" }}>
                        {selectedModelDetail.label}
                      </span>
                    </div>
                    {selectedModelDetail.badge && (
                      <Badge tone={selectedModelDetail.recommended ? "success" : "info"}>
                        {selectedModelDetail.badge}
                      </Badge>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <>
                <input type="hidden" name="aiProvider" value={aiProvider} />
                <input type="hidden" name="model" value={model} />
              </>
            )}

            {/* CHATBOT BRANDING & STOREFRONT WIDGET SETTINGS CARD */}
            <div className="cc-card">
              <div className="cc-card-header">
                <div className="cc-card-title">
                  <div className="cc-card-icon">
                    <FAIcon name="palette" />
                  </div>
                  <span>Chatbot Branding & Storefront Widget Settings</span>
                </div>
                <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
                  <span style={{ fontSize: "11px", color: "#64748b" }}>Live Storefront Configurator</span>
                  <Badge tone="info">Real-Time Sync</Badge>
                </div>
              </div>

              <div className="cc-branding-split">
                {/* SETTINGS FORM INPUTS */}
                <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
                  
                  {/* SECTION 1: HEADER & BOT IDENTITY */}
                  <div>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="robot" style={{ color: "#4f46e5" }} />
                      <span>1. Header & Bot Identity</span>
                    </h4>

                    <div style={{ display: "flex", flexDirection: "column", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Bot Display Name</label>
                        <input
                          type="text"
                          name="botName"
                          className="cc-input"
                          value={botName}
                          onChange={(e) => setBotName(e.target.value)}
                          autoComplete="off"
                          placeholder="ShopPilot AI Assistant"
                        />
                        <div className="cc-subtext">Main title shown at the top of the chat widget header.</div>
                      </div>

                      <div>
                        <label className="cc-label">Header Subtitle / Tagline</label>
                        <textarea
                          name="headerSubtext"
                          className="cc-textarea"
                          rows={2}
                          value={headerSubtext}
                          onChange={(e) => setHeaderSubtext(e.target.value)}
                          placeholder="Get helpful guidance and recommendations from ShopPilot AI generative AI assistant."
                        />
                        <div className="cc-subtext">Brief description text displayed below the bot name on the welcome screen.</div>
                      </div>

                      <div>
                        <label className="cc-label">Header Search Input Placeholder</label>
                        <input
                          type="text"
                          name="headerInputPlaceholder"
                          className="cc-input"
                          value={headerInputPlaceholder}
                          onChange={(e) => setHeaderInputPlaceholder(e.target.value)}
                          autoComplete="off"
                          placeholder="Ask a question"
                        />
                        <div className="cc-subtext">Placeholder text for the search box on the welcome header card.</div>
                      </div>
                    </div>
                  </div>

                  {/* SECTION 2: GETTING STARTED & STARTER PROMPTS */}
                  <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="sparkles" style={{ color: "#f59e0b" }} />
                      <span>2. Getting Started & Starter Prompts</span>
                    </h4>

                    <div style={{ display: "flex", flexDirection: "column", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Getting Started Section Title</label>
                        <input
                          type="text"
                          name="startHeading"
                          className="cc-input"
                          value={startHeading}
                          onChange={(e) => setStartHeading(e.target.value)}
                          autoComplete="off"
                          placeholder="Want help getting started?"
                        />
                      </div>

                      <div>
                        <label className="cc-label">Getting Started Subtitle</label>
                        <input
                          type="text"
                          name="startSubheading"
                          className="cc-input"
                          value={startSubheading}
                          onChange={(e) => setStartSubheading(e.target.value)}
                          autoComplete="off"
                          placeholder="Tell us a little bit about what you're looking for."
                        />
                      </div>

                      <div>
                        <label className="cc-label" style={{ marginBottom: "6px" }}>
                          Quick Action Starter Buttons (Prompt Chips)
                        </label>
                        <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                          <div>
                            <span style={{ fontSize: "11px", fontWeight: 600, color: "#64748b" }}>Prompt 1:</span>
                            <input
                              type="text"
                              name="starterPrompt1"
                              className="cc-input"
                              value={starterPrompt1}
                              onChange={(e) => setStarterPrompt1(e.target.value)}
                              autoComplete="off"
                              placeholder="I want to find products & recommendations"
                            />
                          </div>
                          <div>
                            <span style={{ fontSize: "11px", fontWeight: 600, color: "#64748b" }}>Prompt 2:</span>
                            <input
                              type="text"
                              name="starterPrompt2"
                              className="cc-input"
                              value={starterPrompt2}
                              onChange={(e) => setStarterPrompt2(e.target.value)}
                              autoComplete="off"
                              placeholder="I need technical support or help with my order"
                            />
                          </div>
                          <div>
                            <span style={{ fontSize: "11px", fontWeight: 600, color: "#64748b" }}>Prompt 3:</span>
                            <input
                              type="text"
                              name="starterPrompt3"
                              className="cc-input"
                              value={starterPrompt3}
                              onChange={(e) => setStarterPrompt3(e.target.value)}
                              autoComplete="off"
                              placeholder="I have a shipping, return, or account question"
                            />
                          </div>
                          <div>
                            <span style={{ fontSize: "11px", fontWeight: 600, color: "#64748b" }}>Prompt 4:</span>
                            <input
                              type="text"
                              name="starterPrompt4"
                              className="cc-input"
                              value={starterPrompt4}
                              onChange={(e) => setStarterPrompt4(e.target.value)}
                              autoComplete="off"
                              placeholder="Do you have discount codes available?"
                            />
                          </div>
                        </div>
                        <div className="cc-subtext">Clickable suggestion buttons on the welcome screen. Empty prompts are hidden.</div>
                      </div>
                    </div>
                  </div>

                  {/* SECTION 3: ACTIVE CONVERSATION & INPUT BAR */}
                  <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="comments" style={{ color: "#3b82f6" }} />
                      <span>3. Active Chat & Input Bar</span>
                    </h4>

                    <div style={{ display: "flex", flexDirection: "column", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Welcome Greeting Message</label>
                        <textarea
                          name="welcomeMessage"
                          className="cc-textarea"
                          rows={2}
                          value={welcomeMessage}
                          onChange={(e) => setWelcomeMessage(e.target.value)}
                          placeholder="Hi 👋 How can I help you find products, calculate shipping, or track orders today?"
                        />
                        <div className="cc-subtext">First message delivered by the assistant in active chat.</div>
                      </div>

                      <div>
                        <label className="cc-label">Active Chat Input Placeholder</label>
                        <input
                          type="text"
                          name="chatInputPlaceholder"
                          className="cc-input"
                          value={chatInputPlaceholder}
                          onChange={(e) => setChatInputPlaceholder(e.target.value)}
                          autoComplete="off"
                          placeholder="Ask me anything about products, shipping, orders..."
                        />
                        <div className="cc-subtext">Placeholder text inside the chat text input during an active conversation.</div>
                      </div>

                      <div>
                        <label className="cc-label">Active Chat Footer Terms Notice</label>
                        <input
                          type="text"
                          name="footerTermsText"
                          className="cc-input"
                          value={footerTermsText}
                          onChange={(e) => setFooterTermsText(e.target.value)}
                          autoComplete="off"
                          placeholder="By chatting, you agree to store AI assistant terms."
                        />
                        <div className="cc-subtext">Small disclaimer text below the message input box.</div>
                      </div>

                      {canUseAI ? (
                        <div>
                          <label className="cc-label">Custom AI System Prompt (Optional)</label>
                          <textarea
                            name="systemPrompt"
                            className="cc-textarea"
                            rows={3}
                            value={systemPrompt}
                            onChange={(e) => setSystemPrompt(e.target.value)}
                            placeholder="You are the AI assistant for {{shop_name}}. Help customers discover products, apply discounts, and track orders."
                          />
                          <div className="cc-subtext">Store-specific system prompt instructions and behavioral guidelines for the AI engine.</div>
                        </div>
                      ) : (
                        <input type="hidden" name="systemPrompt" value={systemPrompt} />
                      )}
                    </div>
                  </div>

                  {/* SECTION 4: STORE CUSTOMER SUPPORT & CONTACT INFORMATION */}
                  <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="headset" style={{ color: "#06b6d4" }} />
                      <span>4. Store Customer Support &amp; Contact Details</span>
                    </h4>
                    <p className="cc-subtext" style={{ marginBottom: "12px", marginTop: "2px" }}>
                      These store contact details will be provided to your customers by the AI assistant whenever they ask for help, contact info, or escalation.
                    </p>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Store Support Email</label>
                        <input
                          type="email"
                          name="storeSupportEmail"
                          className="cc-input"
                          value={storeSupportEmail}
                          onChange={(e) => setStoreSupportEmail(e.target.value)}
                          autoComplete="off"
                          placeholder="support@yourstore.com"
                        />
                        <div className="cc-subtext">Store email for customer inquiries & order questions.</div>
                      </div>

                      <div>
                        <label className="cc-label">Store Phone / WhatsApp Helpline</label>
                        <input
                          type="text"
                          name="storeSupportPhone"
                          className="cc-input"
                          value={storeSupportPhone}
                          onChange={(e) => setStoreSupportPhone(e.target.value)}
                          autoComplete="off"
                          placeholder="+1 (555) 234-5678"
                        />
                        <div className="cc-subtext">Direct phone number or WhatsApp support line for customers.</div>
                      </div>

                      <div>
                        <label className="cc-label">Business / Support Operating Hours</label>
                        <input
                          type="text"
                          name="storeSupportHours"
                          className="cc-input"
                          value={storeSupportHours}
                          onChange={(e) => setStoreSupportHours(e.target.value)}
                          autoComplete="off"
                          placeholder="Mon-Fri: 9:00 AM - 6:00 PM EST"
                        />
                        <div className="cc-subtext">Operating hours when your human staff is available.</div>
                      </div>

                      <div>
                        <label className="cc-label">Store Contact Us Page URL</label>
                        <input
                          type="text"
                          name="storeContactUrl"
                          className="cc-input"
                          value={storeContactUrl}
                          onChange={(e) => setStoreContactUrl(e.target.value)}
                          autoComplete="off"
                          placeholder="/pages/contact or https://yourstore.com/pages/contact"
                        />
                        <div className="cc-subtext">Link to your store's Contact Us or help page.</div>
                      </div>

                      <div style={{ gridColumn: "span 2" }}>
                        <label className="cc-label">Store Physical Address / Location (Optional)</label>
                        <input
                          type="text"
                          name="storeAddress"
                          className="cc-input"
                          value={storeAddress}
                          onChange={(e) => setStoreAddress(e.target.value)}
                          autoComplete="off"
                          placeholder="123 Retail Ave, Suite 100, New York, NY 10001"
                        />
                        <div className="cc-subtext">Physical address or headquarters location shared if customers ask.</div>
                      </div>
                    </div>
                  </div>

                  {/* SECTION 5: STORE SHIPPING CHARGES & DELIVERY POLICY */}
                  <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="truck-fast" style={{ color: "#0ea5e9" }} />
                      <span>5. Store Shipping Charges &amp; Delivery Policy</span>
                    </h4>
                    <p className="cc-subtext" style={{ marginBottom: "12px", marginTop: "2px" }}>
                      Configure your store's shipping rates, free shipping threshold, and estimated delivery times. The AI assistant will quote these exact rates and policies to customers who ask about delivery costs.
                    </p>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Free Shipping Threshold</label>
                        <input
                          type="text"
                          name="freeShippingThreshold"
                          className="cc-input"
                          value={freeShippingThreshold}
                          onChange={(e) => setFreeShippingThreshold(e.target.value)}
                          autoComplete="off"
                          placeholder="$50 (or leave empty if no free shipping)"
                        />
                        <div className="cc-subtext">Minimum order amount for free standard delivery (e.g. "$50" or "Rs. 999").</div>
                      </div>

                      <div>
                        <label className="cc-label">Standard Shipping Fee</label>
                        <input
                          type="text"
                          name="standardShippingFee"
                          className="cc-input"
                          value={standardShippingFee}
                          onChange={(e) => setStandardShippingFee(e.target.value)}
                          autoComplete="off"
                          placeholder="$4.99 flat rate"
                        />
                        <div className="cc-subtext">Standard delivery fee for orders below the threshold (e.g. "$4.99 flat rate").</div>
                      </div>

                      <div>
                        <label className="cc-label">Estimated Delivery Timeframe</label>
                        <input
                          type="text"
                          name="estimatedDeliveryDays"
                          className="cc-input"
                          value={estimatedDeliveryDays}
                          onChange={(e) => setEstimatedDeliveryDays(e.target.value)}
                          autoComplete="off"
                          placeholder="2 - 5 business days"
                        />
                        <div className="cc-subtext">Estimated delivery duration for standard domestic shipments.</div>
                      </div>

                      <div>
                        <label className="cc-label">Store Shipping Policy URL</label>
                        <input
                          type="text"
                          name="shippingPolicyUrl"
                          className="cc-input"
                          value={shippingPolicyUrl}
                          onChange={(e) => setShippingPolicyUrl(e.target.value)}
                          autoComplete="off"
                          placeholder="/policies/shipping-policy"
                        />
                        <div className="cc-subtext">Direct link to full shipping terms and policy details.</div>
                      </div>
                    </div>
                  </div>

                  {/* SECTION 6: DISCLAIMER & LEGAL COMPLIANCE */}
                  <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                    <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                      <FAIcon name="shield-halved" style={{ color: "#10b981" }} />
                      <span>6. Disclaimer &amp; Legal Notice</span>
                    </h4>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px", marginTop: "10px" }}>
                      <div>
                        <label className="cc-label">Disclaimer Notice Prefix</label>
                        <input
                          type="text"
                          name="disclaimerText"
                          className="cc-input"
                          value={disclaimerText}
                          onChange={(e) => setDisclaimerText(e.target.value)}
                          autoComplete="off"
                          placeholder="By chatting, you agree to this"
                        />
                      </div>
                      <div>
                        <label className="cc-label">Disclaimer Link Label</label>
                        <input
                          type="text"
                          name="disclaimerLinkText"
                          className="cc-input"
                          value={disclaimerLinkText}
                          onChange={(e) => setDisclaimerLinkText(e.target.value)}
                          autoComplete="off"
                          placeholder="disclaimer"
                        />
                      </div>
                      <div style={{ gridColumn: "span 2" }}>
                        <label className="cc-label">Disclaimer Target Link / URL</label>
                        <input
                          type="text"
                          name="disclaimerUrl"
                          className="cc-input"
                          value={disclaimerUrl}
                          onChange={(e) => setDisclaimerUrl(e.target.value)}
                          autoComplete="off"
                          placeholder="https://yourstore.com/pages/terms or #"
                        />
                        <div className="cc-subtext">Clicking the disclaimer opens this URL in a new tab (or set # to disable link).</div>
                      </div>
                    </div>
                  </div>

                  {/* SECTION 7: WIDGET ACTION MENU */}
                  <div style={{ display: "flex", gap: "20px" }}>
                    <div style={{ width: "100%" }}>
                      <div>
                        <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                          <FAIcon name="bars" style={{ color: "#6366f1" }} />
                          <span>7. Widget Options Menu</span>
                        </h4>

                        <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "12px", marginTop: "10px" }}>
                          <div>
                            <label className="cc-label">Support Menu Item Label</label>
                            <input
                              type="text"
                              name="supportMenuItemText"
                              className="cc-input"
                              value={supportMenuItemText}
                              onChange={(e) => setSupportMenuItemText(e.target.value)}
                              autoComplete="off"
                              placeholder="Contact store support"
                            />
                          </div>
                          <div>
                            <label className="cc-label">Clear Chat Menu Item Label</label>
                            <input
                              type="text"
                              name="clearMenuItemText"
                              className="cc-input"
                              value={clearMenuItemText}
                              onChange={(e) => setClearMenuItemText(e.target.value)}
                              autoComplete="off"
                              placeholder="Clear conversation"
                            />
                          </div>
                        </div>
                      </div>

                      {/* SECTION 8: CUSTOMER LOGIN & REGISTRATION (STARTER & PRO ONLY) */}
                      {canUseCustomerAuth ? (
                        <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                            <div>
                              <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "8px", margin: 0 }}>
                                <FAIcon name="user" style={{ color: "#4f46e5" }} />
                                <span>8. Customer Login &amp; Registration</span>
                              </h4>
                            </div>
                          </div>

                          <div style={{ background: "#F8FAFC", border: "1px solid #E2E8F0", borderRadius: "12px", padding: "16px", marginTop: "12px" }}>
                            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                              <div>
                                <div style={{ fontSize: "13px", fontWeight: 700, color: "#1E293B" }}>
                                  Status: <span style={{ color: customerAuthEnabled ? "#059669" : "#64748B" }}>{customerAuthEnabled ? "Active" : "Inactive"}</span>
                                </div>
                                <div style={{ fontSize: "12px", color: "#64748B", marginTop: "2px" }}>
                                  {customerAuthEnabled
                                    ? "Active: The Login/Register option is shown in the chatbot and customers can use the authentication flow."
                                    : "Inactive: Login/Register is hidden from the customer-facing chatbot."}
                                </div>
                              </div>

                              {/* Active / Inactive Segmented Buttons */}
                              <div style={{ display: "inline-flex", background: "#E2E8F0", padding: "3px", borderRadius: "8px", gap: "2px" }}>
                                <button
                                  type="button"
                                  onClick={() => setCustomerAuthEnabled(true)}
                                  style={{
                                    border: "none",
                                    background: customerAuthEnabled ? "#10B981" : "transparent",
                                    color: customerAuthEnabled ? "#FFFFFF" : "#64748B",
                                    fontWeight: 700,
                                    fontSize: "12px",
                                    padding: "6px 14px",
                                    borderRadius: "6px",
                                    cursor: "pointer",
                                    transition: "all 0.15s ease",
                                  }}
                                >
                                  Active
                                </button>
                                <button
                                  type="button"
                                  onClick={() => setCustomerAuthEnabled(false)}
                                  style={{
                                    border: "none",
                                    background: !customerAuthEnabled ? "#64748B" : "transparent",
                                    color: !customerAuthEnabled ? "#FFFFFF" : "#64748B",
                                    fontWeight: 700,
                                    fontSize: "12px",
                                    padding: "6px 14px",
                                    borderRadius: "6px",
                                    cursor: "pointer",
                                    transition: "all 0.15s ease",
                                  }}
                                >
                                  Inactive
                                </button>
                              </div>
                            </div>
                            <input type="hidden" name="customerAuthEnabled" value={customerAuthEnabled ? "true" : "false"} />
                          </div>
                        </div>
                      ) : (
                        <input type="hidden" name="customerAuthEnabled" value="false" />
                      )}

                      {/* SECTION 9: COLOR PALETTE & APPEARANCE */}
                      <div style={{ borderTop: "1px solid #f1f5f9", paddingTop: "18px" }}>
                        <h4 className="cc-section-subtitle" style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                          <FAIcon name="paint-roller" style={{ color: "#ec4899" }} />
                          <span>{canUseCustomerAuth ? "9" : "8"}. Theme Colors &amp; Appearance</span>
                        </h4>

                        {/* COLOR PALETTE CONTROLS GRID */}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "12px", marginTop: "10px" }}>
                          {/* Primary Accent Color */}
                          <div>
                            <label className="cc-label">Primary Accent Color</label>
                            <div className="cc-color-group">
                              <input
                                type="color"
                                className="cc-color-swatch-input"
                                value={primaryColor && primaryColor.startsWith("#") ? primaryColor : "#4F46E5"}
                                onChange={(e) => setPrimaryColor((e.target as HTMLInputElement).value)}
                              />
                              <input
                                type="text"
                                name="primaryColor"
                                className="cc-input"
                                value={primaryColor}
                                onChange={(e) => setPrimaryColor(e.target.value)}
                                autoComplete="off"
                                placeholder="#4F46E5"
                              />
                            </div>
                            <div className="cc-subtext">Header gradient start & user buttons</div>
                          </div>

                          {/* Secondary Accent Color */}
                          <div>
                            <label className="cc-label">Secondary Accent Color</label>
                            <div className="cc-color-group">
                              <input
                                type="color"
                                className="cc-color-swatch-input"
                                value={secondaryColor && secondaryColor.startsWith("#") ? secondaryColor : "#4338CA"}
                                onChange={(e) => setSecondaryColor((e.target as HTMLInputElement).value)}
                              />
                              <input
                                type="text"
                                name="secondaryColor"
                                className="cc-input"
                                value={secondaryColor}
                                onChange={(e) => setSecondaryColor(e.target.value)}
                                autoComplete="off"
                                placeholder="#4338CA"
                              />
                            </div>
                            <div className="cc-subtext">Header gradient end & borders</div>
                          </div>

                          {/* Header & User Text Color */}
                          <div>
                            <label className="cc-label">Header Text Color</label>
                            <div className="cc-color-group">
                              <input
                                type="color"
                                className="cc-color-swatch-input"
                                value={textColor && textColor.startsWith("#") ? textColor : "#FFFFFF"}
                                onChange={(e) => setTextColor((e.target as HTMLInputElement).value)}
                              />
                              <input
                                type="text"
                                name="textColor"
                                className="cc-input"
                                value={textColor}
                                onChange={(e) => setTextColor(e.target.value)}
                                autoComplete="off"
                                placeholder="#FFFFFF"
                              />
                            </div>
                            <div className="cc-subtext">Text on header & dark backgrounds</div>
                          </div>

                          {/* Bot Message Text Color */}
                          <div>
                            <label className="cc-label">Bot Message Text Color</label>
                            <div className="cc-color-group">
                              <input
                                type="color"
                                className="cc-color-swatch-input"
                                value={botTextColor && botTextColor.startsWith("#") ? botTextColor : "#1F2937"}
                                onChange={(e) => setBotTextColor((e.target as HTMLInputElement).value)}
                              />
                              <input
                                type="text"
                                name="botTextColor"
                                className="cc-input"
                                value={botTextColor}
                                onChange={(e) => setBotTextColor(e.target.value)}
                                autoComplete="off"
                                placeholder="#1F2937"
                              />
                            </div>
                            <div className="cc-subtext">Text in bot bubbles & prompt buttons</div>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    {/* LIVE CHATBOT STOREFRONT PREVIEW */}
                    <div className="cc-preview-frame">
                      <div className="cc-preview-title-bar" style={{ display: "flex", flexDirection: "column", gap: "10px", padding: "4px 4px 12px 4px" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                          <div style={{ display: "flex", alignItems: "center", gap: "8px", fontSize: "12px", fontWeight: 700, color: "#F8FAFC", letterSpacing: "0.01em" }}>
                            <FAIcon name="mobile-screen" style={{ color: "#818CF8" }} />
                            <span>Live Storefront Preview</span>
                          </div>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: "5px", color: enabled ? "#34D399" : "#F87171", fontSize: "11px", fontWeight: 600, background: enabled ? "rgba(16, 185, 129, 0.15)" : "rgba(239, 68, 68, 0.15)", padding: "2px 8px", borderRadius: "12px", border: `1px solid ${enabled ? "rgba(16, 185, 129, 0.3)" : "rgba(239, 68, 68, 0.3)"}` }}>
                            <span style={{ width: "6px", height: "6px", borderRadius: "50%", background: enabled ? "#10B981" : "#EF4444", display: "inline-block" }}></span>
                            {enabled ? "Live (Visible)" : "Hidden (Inactive)"}
                          </span>
                        </div>

                        {/* Preview View Switcher Segmented Tabs */}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", background: "rgba(255, 255, 255, 0.08)", padding: "3px", borderRadius: "10px", gap: "4px" }}>
                          <button
                            type="button"
                            style={{
                              border: "none",
                              background: previewTab === "welcome" ? "#FFFFFF" : "transparent",
                              color: previewTab === "welcome" ? "#0F172A" : "#94A3B8",
                              fontWeight: previewTab === "welcome" ? 700 : 500,
                              fontSize: "12px",
                              padding: "6px 10px",
                              borderRadius: "8px",
                              cursor: "pointer",
                              transition: "all 0.15s ease",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              gap: "6px",
                              whiteSpace: "nowrap",
                              boxShadow: previewTab === "welcome" ? "0 2px 4px rgba(0,0,0,0.25)" : "none",
                            }}
                            onClick={() => setPreviewTab("welcome")}
                          >
                            <FAIcon name="mobile-screen" />
                            <span>Getting Started</span>
                          </button>
                          <button
                            type="button"
                            style={{
                              border: "none",
                              background: previewTab === "active" ? "#FFFFFF" : "transparent",
                              color: previewTab === "active" ? "#0F172A" : "#94A3B8",
                              fontWeight: previewTab === "active" ? 700 : 500,
                              fontSize: "12px",
                              padding: "6px 10px",
                              borderRadius: "8px",
                              cursor: "pointer",
                              transition: "all 0.15s ease",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              gap: "6px",
                              whiteSpace: "nowrap",
                              boxShadow: previewTab === "active" ? "0 2px 4px rgba(0,0,0,0.25)" : "none",
                            }}
                            onClick={() => setPreviewTab("active")}
                          >
                            <FAIcon name="comments" />
                            <span>Active Chat</span>
                          </button>
                        </div>
                      </div>

                      <div className="cc-widget-mockup" style={{ display: "flex", flexDirection: "column", minHeight: "440px", maxHeight: "540px" }}>
                        
                        {previewTab === "welcome" ? (
                          /* 📱 GETTING STARTED VIEW (MATCHES UPLOADED SCREENSHOT) */
                          <div style={{ display: "flex", flexDirection: "column", height: "100%", flex: 1, backgroundColor: "#ffffff" }}>
                            {/* AWS Header Card */}
                            <div
                              style={{
                                background: `linear-gradient(135deg, ${primaryColor || "#4F46E5"}, ${secondaryColor || "#4338CA"})`,
                                color: textColor || "#FFFFFF",
                                padding: "20px 18px",
                                borderTopLeftRadius: "10px",
                                borderTopRightRadius: "10px",
                              }}
                            >
                              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                  <div style={{ width: "24px", height: "24px", borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px" }}>
                                    <FAIcon name="ellipsis" />
                                  </div>
                                  <h3 style={{ margin: 0, fontSize: "16px", fontWeight: 800, color: textColor || "#FFFFFF", letterSpacing: "-0.01em" }}>
                                    {botName || "ShopPilot AI Assistant"}
                                  </h3>
                                </div>
                                <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                  {canUseCustomerAuth && customerAuthEnabled && (
                                    <div style={{ width: "24px", height: "24px", borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px", color: textColor || "#FFFFFF" }}>
                                      <FAIcon name="user" />
                                    </div>
                                  )}
                                  <div style={{ width: "24px", height: "24px", borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px" }}>
                                    <FAIcon name="minus" />
                                  </div>
                                </div>
                              </div>

                              <p style={{ margin: "0 0 14px 0", fontSize: "12px", opacity: 0.92, lineHeight: 1.45, color: textColor || "#FFFFFF" }}>
                                {headerSubtext || "Get helpful guidance and recommendations from ShopPilot AI generative AI assistant."}
                              </p>

                              <div style={{ display: "flex", alignItems: "center", background: "#FFFFFF", borderRadius: "24px", padding: "4px 6px 4px 14px", boxShadow: "0 4px 12px rgba(0,0,0,0.12)" }}>
                                <input
                                  type="text"
                                  readOnly
                                  placeholder={headerInputPlaceholder || "Ask a question"}
                                  style={{ flex: 1, border: "none", background: "transparent", fontSize: "12px", color: "#111827", outline: "none" }}
                                />
                                <div style={{ width: "28px", height: "28px", borderRadius: "50%", background: primaryColor || "#4F46E5", color: textColor || "#FFFFFF", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px" }}>
                                  <FAIcon name="arrow-right" />
                                </div>
                              </div>
                            </div>

                            {/* Getting Started Body & Prompt Chips */}
                            <div style={{ padding: "18px 16px", flex: 1, display: "flex", flexDirection: "column", justifyContent: "space-between", background: "#ffffff" }}>
                              <div>
                                {canUseCustomerAuth && customerAuthEnabled && (
                                  <div
                                    style={{
                                      background: "#F8FAFC",
                                      border: "1.5px solid #E2E8F0",
                                      borderRadius: "10px",
                                      padding: "10px 12px",
                                      marginBottom: "14px",
                                      display: "flex",
                                      alignItems: "center",
                                      justifyContent: "space-between",
                                    }}
                                  >
                                    <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                      <div style={{ width: "24px", height: "24px", borderRadius: "50%", background: "rgba(79, 70, 229, 0.12)", color: primaryColor || "#4F46E5", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "11px" }}>
                                        <FAIcon name="user" />
                                      </div>
                                      <div>
                                        <div style={{ fontSize: "11.5px", fontWeight: 700, color: "#1E293B" }}>Customer Account</div>
                                        <div style={{ fontSize: "10.5px", color: "#64748B" }}>Sign in or register for order tracking</div>
                                      </div>
                                    </div>
                                    <span style={{ fontSize: "11px", fontWeight: 700, color: primaryColor || "#4F46E5", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                      <span>Sign In</span>
                                      <FAIcon name="arrow-right" size="xs" />
                                    </span>
                                  </div>
                                )}

                                <div style={{ marginBottom: "12px" }}>
                                  <h4 style={{ margin: "0 0 4px 0", fontSize: "14px", fontWeight: 700, color: "#111827" }}>
                                    {startHeading || "Want help getting started?"}
                                  </h4>
                                  <p style={{ margin: 0, fontSize: "12px", color: "#6b7280" }}>
                                    {startSubheading || "Tell us a little bit about what you're looking for."}
                                  </p>
                                </div>

                                <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                                  {[starterPrompt1, starterPrompt2, starterPrompt3, starterPrompt4]
                                    .filter((p) => p && p.trim().length > 0)
                                    .map((prompt, idx) => (
                                      <div
                                        key={idx}
                                        style={{
                                          background: "#ffffff",
                                          border: "1.5px solid #E5E7EB",
                                          borderRadius: "10px",
                                          padding: "10px 14px",
                                          fontSize: "12px",
                                          fontWeight: 500,
                                          color: botTextColor || "#1F2937",
                                          boxShadow: "0 1px 3px rgba(0,0,0,0.03)",
                                          cursor: "pointer",
                                        }}
                                      >
                                        {prompt}
                                      </div>
                                    ))}
                                </div>
                              </div>

                              <div style={{ fontSize: "11px", color: "#9ca3af", textAlign: "center", marginTop: "14px" }}>
                                {disclaimerText || "By chatting, you agree to this"}{" "}
                                <span style={{ color: primaryColor || "#4F46E5", textDecoration: "underline", fontWeight: 600 }}>
                                  {disclaimerLinkText || "disclaimer"}
                                </span>.
                              </div>
                            </div>
                          </div>
                        ) : (
                          /* 💬 ACTIVE CHAT STREAM VIEW */
                          <div style={{ display: "flex", flexDirection: "column", height: "100%", flex: 1, backgroundColor: "#ffffff" }}>
                            <div 
                              className="cc-widget-header" 
                              style={{ 
                                background: `linear-gradient(135deg, ${primaryColor || "#4F46E5"}, ${secondaryColor || "#4338CA"})`,
                                color: textColor || "#FFFFFF" 
                              }}
                            >
                              <div className="cc-widget-header-bot">
                                <div className="cc-widget-avatar" style={{ background: "rgba(255,255,255,0.2)", color: textColor || "#FFFFFF" }}>
                                  <FAIcon name="robot" />
                                </div>
                                <div>
                                  <div style={{ fontWeight: 700, fontSize: "0.88rem", color: textColor || "#FFFFFF" }}>{botName || "ShopPilot AI Assistant"}</div>
                                  <div style={{ fontSize: "0.72rem", opacity: 0.85, color: textColor || "#FFFFFF" }}>Online & ready to help</div>
                                </div>
                              </div>
                              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                {canUseCustomerAuth && customerAuthEnabled && (
                                  <FAIcon name="user" style={{ cursor: "pointer", opacity: 0.9, color: textColor || "#FFFFFF", fontSize: "12px" }} />
                                )}
                                <FAIcon name="xmark" style={{ cursor: "pointer", opacity: 0.8, color: textColor || "#FFFFFF" }} />
                              </div>
                            </div>

                            {showCartSummary && (
                              <div style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0", padding: "6px 12px", display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: "11px", color: "#475569" }}>
                                <span style={{ display: "flex", alignItems: "center", gap: "5px" }}>
                                  <FAIcon name="cart-shopping" style={{ fontSize: "11px", color: "#64748b" }} /> Cart: 0 item(s) (INR 0.00)
                                </span>
                                <span style={{ color: "#059669", fontWeight: 700, display: "flex", alignItems: "center", gap: "3px" }}>
                                  <FAIcon name="bolt" style={{ fontSize: "10px" }} /> Checkout
                                </span>
                              </div>
                            )}

                            <div className="cc-widget-body" style={{ flex: 1, overflowY: "auto", padding: "12px" }}>
                              <div className="cc-widget-msg bot" style={{ color: botTextColor || "#1F2937" }}>
                                {welcomeMessage || "Hi 👋 How can I help you find products, calculate shipping, or track orders today?"}
                              </div>

                              <div 
                                className="cc-widget-msg user" 
                                style={{ 
                                  backgroundColor: primaryColor || "#4F46E5",
                                  color: textColor || "#FFFFFF"
                                }}
                              >
                                Can you help me find trending products?
                              </div>

                              <div className="cc-widget-msg bot" style={{ color: botTextColor || "#1F2937" }}>
                                <div style={{ fontWeight: 600, marginBottom: "4px" }}>Featured Recommendation:</div>
                                <div style={{ background: "#f8fafc", border: `1px solid ${secondaryColor ? secondaryColor + "40" : "#e2e8f0"}`, borderRadius: "8px", padding: "8px", display: "flex", gap: "8px", alignItems: "center" }}>
                                  <div style={{ width: "32px", height: "32px", background: "#e0e7ff", borderRadius: "6px", display: "flex", alignItems: "center", justifyContent: "center", color: primaryColor || "#4F46E5" }}>
                                    <FAIcon name="bag-shopping" size="sm" />
                                  </div>
                                  <div>
                                    <div style={{ fontWeight: 600, fontSize: "0.78rem" }}>AeroStride Pro</div>
                                    <div style={{ color: "#059669", fontSize: "0.75rem", fontWeight: 700 }}>$129.99</div>
                                  </div>
                                </div>
                              </div>
                            </div>

                            <div className="cc-widget-input-bar" style={{ padding: "8px 12px", borderTop: "1px solid #f1f5f9" }}>
                              <div className="cc-widget-input-placeholder" style={{ fontSize: "11px", color: "#9ca3af" }}>
                                {chatInputPlaceholder || "Ask me anything about products, shipping, orders..."}
                              </div>
                              <div style={{ width: "26px", height: "26px", borderRadius: "50%", background: primaryColor || "#4F46E5", color: textColor || "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "10px" }}>
                                <FAIcon name="paper-plane" />
                              </div>
                            </div>

                            <div style={{ padding: "4px 8px 6px", textAlign: "center", fontSize: "0.68rem", color: "#94a3b8", background: "#ffffff", borderTop: "1px solid #f1f5f9" }}>
                              {(showPoweredBy || !canRemoveBranding) && (
                                <div style={{ marginBottom: "2px", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                                  <FAIcon name="bolt" size="xs" style={{ color: "#4F46E5" }} />
                                  <span>Powered by <strong style={{ color: "#475569" }}>ShopPilot AI</strong></span>
                                </div>
                              )}
                              <div>{footerTermsText || "By chatting, you agree to store AI assistant terms."}</div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Live Cart Summary & Instant Checkout Bar Toggle */}
                  <div style={{ marginTop: "16px", padding: "16px", borderRadius: "12px", border: "1px solid #e2e8f0", background: "#f8fafc" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <div style={{ fontWeight: 700, fontSize: "0.88rem", color: "#1e293b", display: "flex", alignItems: "center", gap: "8px" }}>
                          <span style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                            <FAIcon name="cart-shopping" style={{ color: "#4F46E5" }} /> Live Cart Summary &amp; Checkout Bar:
                          </span>
                          <span style={{ color: showCartSummary ? "#059669" : "#64748B", fontWeight: 700 }}>
                            {showCartSummary ? "Active (Show)" : "Inactive (Hide)"}
                          </span>
                        </div>
                        <div style={{ fontSize: "0.76rem", color: "#64748b", marginTop: "4px" }}>
                          {showCartSummary
                            ? "Active: Live cart items count, total amount, and instant checkout button are displayed in the chat header."
                            : "Inactive: Cart summary is hidden from the chat header."}
                        </div>
                      </div>

                      <div style={{ display: "inline-flex", background: "#E2E8F0", padding: "3px", borderRadius: "8px", gap: "2px" }}>
                        <button
                          type="button"
                          onClick={() => setShowCartSummary(true)}
                          style={{
                            border: "none",
                            background: showCartSummary ? "#10B981" : "transparent",
                            color: showCartSummary ? "#FFFFFF" : "#64748B",
                            fontWeight: 700,
                            fontSize: "12px",
                            padding: "6px 14px",
                            borderRadius: "6px",
                            cursor: "pointer",
                            transition: "all 0.15s ease",
                          }}
                        >
                          Show
                        </button>
                        <button
                          type="button"
                          onClick={() => setShowCartSummary(false)}
                          style={{
                            border: "none",
                            background: !showCartSummary ? "#64748B" : "transparent",
                            color: !showCartSummary ? "#FFFFFF" : "#64748B",
                            fontWeight: 700,
                            fontSize: "12px",
                            padding: "6px 14px",
                            borderRadius: "6px",
                            cursor: "pointer",
                            transition: "all 0.15s ease",
                          }}
                        >
                          Hide
                        </button>
                      </div>
                    </div>
                    <input type="hidden" name="showCartSummary" value={showCartSummary ? "true" : "false"} />
                  </div>

                  {/* Chatbot Widget Display Status (Active / Inactive) */}
                  <div style={{ marginTop: "16px", padding: "16px", borderRadius: "12px", border: "1px solid #e2e8f0", background: "#f8fafc" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <div style={{ fontWeight: 700, fontSize: "0.88rem", color: "#1e293b", display: "flex", alignItems: "center", gap: "8px" }}>
                          <span style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                            <FAIcon name="robot" style={{ color: "#4F46E5" }} /> Chatbot Widget Display:
                          </span>
                          {loaderData.isChatbotAdminDisabled ? (
                            <span style={{ color: "#DC2626", fontWeight: 700, display: "inline-flex", alignItems: "center", gap: "5px" }}>
                              <FAIcon name="ban" /> Locked (Deactivated by SaaS Admin)
                            </span>
                          ) : (
                            <span style={{ color: enabled ? "#059669" : "#DC2626", fontWeight: 700, display: "inline-flex", alignItems: "center", gap: "5px" }}>
                              {enabled ? (
                                <>
                                  <FAIcon name="circle-check" /> Active (Show)
                                </>
                              ) : (
                                <>
                                  <FAIcon name="circle-xmark" /> Inactive (Hide)
                                </>
                              )}
                            </span>
                          )}
                        </div>
                        <div style={{ fontSize: "0.76rem", color: "#64748b", marginTop: "4px" }}>
                          {loaderData.isChatbotAdminDisabled
                            ? "Chatbot has been deactivated by SaaS platform administration. Merchants cannot enable the chatbot while deactivated by SaaS Admin. Please contact SaaS Support to reactivate."
                            : enabled
                            ? "Active: Chatbot widget is visible and fully responsive on your storefront."
                            : "Inactive: Chatbot widget is completely disabled and hidden from customers on your storefront."}
                        </div>
                      </div>

                      <div>
                        {loaderData.isChatbotAdminDisabled ? (
                          <div style={{ display: "inline-flex", alignItems: "center", gap: "6px", color: "#dc2626", fontSize: "12px", fontWeight: 700, padding: "6px 12px", background: "#fee2e2", border: "1px solid #fecaca", borderRadius: "8px" }}>
                            <FAIcon name="lock" />
                            <span>Locked by SaaS Admin</span>
                          </div>
                        ) : (
                          <div style={{ display: "inline-flex", background: "#E2E8F0", padding: "3px", borderRadius: "8px", gap: "2px" }}>
                            <button
                              type="button"
                              onClick={() => setEnabled(true)}
                              style={{
                                border: "none",
                                background: enabled ? "#10B981" : "transparent",
                                color: enabled ? "#FFFFFF" : "#64748B",
                                fontWeight: 700,
                                fontSize: "12px",
                                padding: "6px 14px",
                                borderRadius: "6px",
                                cursor: "pointer",
                                transition: "all 0.15s ease",
                              }}
                            >
                              Active
                            </button>
                            <button
                              type="button"
                              onClick={() => setEnabled(false)}
                              style={{
                                border: "none",
                                background: !enabled ? "#EF4444" : "transparent",
                                color: !enabled ? "#FFFFFF" : "#64748B",
                                fontWeight: 700,
                                fontSize: "12px",
                                padding: "6px 14px",
                                borderRadius: "6px",
                                cursor: "pointer",
                                transition: "all 0.15s ease",
                              }}
                            >
                              Inactive
                            </button>
                          </div>
                        )}
                      </div>
                    </div>
                    <input type="hidden" name="enabled" value={loaderData.isChatbotAdminDisabled ? "false" : (enabled ? "true" : "false")} />
                  </div>

                  {/* Chatbot Screen Alignment (Left / Right Side) */}
                  <div style={{ marginTop: "16px", padding: "12px 14px", borderRadius: "8px", border: "1px solid #e2e8f0", background: "#f8fafc" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: "0.84rem", color: "#1e293b", display: "flex", alignItems: "center", gap: "8px" }}>
                          <span>Chatbot Widget Position</span>
                          <Badge tone="info">
                            {position === "bottom-left" || position === "left" ? "Left Side" : "Right Side"}
                          </Badge>
                        </div>
                        <div style={{ fontSize: "0.74rem", color: "#64748b", marginTop: "3px" }}>
                          Choose whether the floating chatbot widget launcher appears on the left or right side of your storefront.
                        </div>
                      </div>

                      <div style={{ display: "flex", gap: "6px" }}>
                        <button
                          type="button"
                          onClick={() => setPosition("bottom-left")}
                          className={`cc-btn ${position === "bottom-left" || position === "left" ? "cc-btn-primary" : "cc-btn-secondary"}`}
                          style={{
                            fontSize: "11px",
                            padding: "4px 10px",
                            borderRadius: "6px",
                            border: (position === "bottom-left" || position === "left") ? "1px solid #4f46e5" : "1px solid #cbd5e1",
                            background: (position === "bottom-left" || position === "left") ? "#4f46e5" : "#ffffff",
                            color: (position === "bottom-left" || position === "left") ? "#ffffff" : "#475569",
                            fontWeight: 600,
                            cursor: "pointer",
                            display: "inline-flex",
                            alignItems: "center",
                            gap: "5px",
                          }}
                        >
                          <FAIcon name="arrow-left" size="xs" />
                          <span>Left Side</span>
                        </button>
                        <button
                          type="button"
                          onClick={() => setPosition("bottom-right")}
                          className={`cc-btn ${position === "bottom-right" || position === "right" ? "cc-btn-primary" : "cc-btn-secondary"}`}
                          style={{
                            fontSize: "11px",
                            padding: "4px 10px",
                            borderRadius: "6px",
                            border: (position === "bottom-right" || position === "right") ? "1px solid #4f46e5" : "1px solid #cbd5e1",
                            background: (position === "bottom-right" || position === "right") ? "#4f46e5" : "#ffffff",
                            color: (position === "bottom-right" || position === "right") ? "#ffffff" : "#475569",
                            fontWeight: 600,
                            cursor: "pointer",
                            display: "inline-flex",
                            alignItems: "center",
                            gap: "5px",
                          }}
                        >
                          <span>Right Side</span>
                          <FAIcon name="arrow-right" size="xs" />
                        </button>
                      </div>
                    </div>
                    <input type="hidden" name="position" value={position} />
                  </div>

                  {/* Powered by ShopPilot AI Branding Watermark */}
                  <div style={{ marginTop: "16px", padding: "12px 14px", borderRadius: "8px", border: "1px solid #e2e8f0", background: "#f8fafc" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: "0.84rem", color: "#1e293b", display: "flex", alignItems: "center", gap: "8px" }}>
                          <span>"Powered by ShopPilot AI" Badge</span>
                          {!canRemoveBranding ? (
                            <Badge tone="attention">Required on Free Plan</Badge>
                          ) : (
                            <Badge tone="success">{`Included in ${loaderData.planTier}`}</Badge>
                          )}
                        </div>
                        <div style={{ fontSize: "0.74rem", color: "#64748b", marginTop: "3px" }}>
                          {!canRemoveBranding
                            ? "Branding watermark is active on the Free plan. Upgrade to remove it."
                            : "Show or hide the ShopPilot AI branding link in the chat widget footer."}
                        </div>
                      </div>

                      <div>
                        {!canRemoveBranding ? (
                          <button
                            type="button"
                            className="cc-btn cc-btn-secondary"
                            style={{ fontSize: "11px", padding: "4px 8px", display: "inline-flex", alignItems: "center", gap: "5px" }}
                            onClick={() => setShowPlansModal(true)}
                          >
                            <FAIcon name="bolt" size="xs" style={{ color: "#4f46e5" }} />
                            <span>Upgrade Plan</span>
                          </button>
                        ) : (
                          <label style={{ display: "flex", alignItems: "center", gap: "6px", cursor: "pointer", fontSize: "12px", fontWeight: 600, color: "#334155" }}>
                            <input
                              type="checkbox"
                              checked={showPoweredBy}
                              onChange={(e) => handleShowPoweredByChange(e.target.checked)}
                              style={{ width: "15px", height: "15px", accentColor: "#4f46e5", cursor: "pointer" }}
                            />
                            <span>{showPoweredBy ? "Show" : "Hide"}</span>
                          </label>
                        )}
                      </div>
                    </div>
                    <input type="hidden" name="showPoweredBy" value={canRemoveBranding ? (showPoweredBy ? "true" : "false") : "true"} />
                  </div>
                </div>
              </div>

              {/* SAVE BUTTON BAR */}
              <div style={{ marginTop: "20px", paddingTop: "14px", borderTop: "1px solid #e1e3e5", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div>
                  <Badge tone={isSaving ? "info" : isDirty ? "attention" : "success"}>
                    {isSaving ? "Saving configuration..." : isDirty ? "Unsaved changes" : "Configuration saved"}
                  </Badge>
                </div>
                <button type="submit" className="cc-btn cc-btn-primary">
                  <FAIcon name="floppy-disk" />
                  Save AI Provider & Branding Settings
                </button>
              </div>
            </div>
          </Form>

          {/* PLAN PURCHASE HISTORY CARD - Only show if the store has purchase history beyond initial default free plan */}
          {(() => {
            const history = loaderData.billingSummary?.subscriptionHistory || [];
            const hasPurchasedPlans = history.length > 0 && history.some((sub: any) => sub.plan !== "FREE" || sub.price > 0 || sub.status === "REPLACED" || sub.status === "EXPIRED");
            if (!hasPurchasedPlans) return null;

            return (
              <div className="cc-card" style={{ marginTop: "20px" }}>
                <div className="cc-card-header">
                  <div className="cc-card-title">
                    <div className="cc-card-icon" style={{ background: "#f8fafc", color: "#4f46e5" }}>
                      <FAIcon name="clock-rotate-left" />
                    </div>
                    <span>Plan Purchase History ({history.length})</span>
                  </div>
                </div>

                <p style={{ fontSize: "13px", color: "#64748b", margin: "0 0 16px 0" }}>
                  Complete history of all plans purchased by your store. Shopify replaces previous subscriptions upon plan change while preserving full audit history.
                </p>

                <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                  {history.map((sub: any) => {
                    const isAct = sub.status === "ACTIVE";
                    const isRep = sub.status === "REPLACED";
                    const isExp = sub.status === "EXPIRED";

                    return (
                      <div
                        key={sub.id}
                        style={{
                          padding: "14px",
                          borderRadius: "8px",
                          border: isAct ? "2px solid #4f46e5" : "1px solid #e2e8f0",
                          background: isAct ? "#eef2ff" : "#ffffff",
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "center",
                        }}
                      >
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                            <strong style={{ fontSize: "14px", color: "#1e293b" }}>{sub.plan} Plan</strong>
                            <span style={{ fontSize: "13px", fontWeight: 700, color: "#4f46e5" }}>${sub.price}/mo</span>
                            <Badge tone={isAct ? "success" : isRep ? "info" : isExp ? "warning" : "critical"}>
                              {sub.status}
                            </Badge>
                          </div>
                          <div style={{ fontSize: "11px", color: "#64748b", marginTop: "4px" }}>
                            Purchased: {new Date(sub.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                            {sub.plan !== "FREE" && sub.plan !== "STARTER" ? ` • Allocation: ${sub.monthlyLimit.toLocaleString()} msgs/mo` : ""}
                          </div>
                        </div>

                        <button
                          type="button"
                          className="cc-btn cc-btn-secondary"
                          style={{ fontSize: "12px", padding: "6px 12px" }}
                          onClick={() => setSelectedHistorySub(sub)}
                        >
                          View Details
                        </button>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })()}

          {/* PAYMENT HISTORY CARD - Only show if there are actual payments recorded */}
          {(() => {
            const payments = loaderData.billingSummary?.payments || [];
            if (payments.length === 0) return null;

            return (
              <div className="cc-card" style={{ marginTop: "20px" }}>
                <div className="cc-card-header">
                  <div className="cc-card-title">
                    <div className="cc-card-icon" style={{ background: "#ecfdf5", color: "#059669" }}>
                      <FAIcon name="file-invoice-dollar" />
                    </div>
                    <span>Payment &amp; Invoice History ({payments.length})</span>
                  </div>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                  {payments.map((pay: any) => (
                    <div
                      key={pay.id}
                      style={{
                        padding: "12px",
                        borderRadius: "8px",
                        border: "1px solid #e2e8f0",
                        background: "#ffffff",
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                      }}
                    >
                      <div>
                        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                          <strong style={{ fontSize: "13px", color: "#0f172a" }}>${pay.amount.toFixed(2)} USD</strong>
                          <span className="cc-subtext" style={{ fontWeight: 600, color: "#059669", display: "inline-flex", alignItems: "center", gap: "4px" }}>
                            <FAIcon name="circle-check" size="xs" />
                            <span>{pay.status}</span>
                          </span>
                          <span style={{ fontSize: "11px", color: "#64748b", fontFamily: "monospace" }}>{pay.invoices?.[0]?.invoiceNumber || pay.id.slice(0, 8)}</span>
                        </div>
                        <div style={{ fontSize: "11px", color: "#64748b", marginTop: "2px" }}>
                          Paid on: {new Date(pay.paidAt || pay.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                        </div>
                      </div>

                      <button
                        type="button"
                        className="cc-btn cc-btn-secondary"
                        style={{ fontSize: "11px", padding: "4px 10px" }}
                        onClick={() => setSelectedPaymentReceipt(pay)}
                      >
                        View Receipt
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            );
          })()}
        </div>

        {/* RIGHT 30% SIDEBAR COLUMN */}
        <div>
          {/* STORE PERFORMANCE STATS */}
          <div className="cc-card">
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon">
                  <FAIcon name="chart-simple" />
                </div>
                <span>Store Performance</span>
              </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
              
              <div className="cc-stat-box">
                <div>
                  <div className="cc-stat-lbl">Total Conversations</div>
                  <div className="cc-stat-val">{loaderData.conversationCount}</div>
                  <div style={{ fontSize: "0.72rem", color: "#3b82f6", fontWeight: 600, marginTop: "2px" }}>
                    <FAIcon name="comments" /> Active AI sessions
                  </div>
                </div>
                <div className="cc-stat-icon" style={{ background: "#eff6ff", color: "#3b82f6" }}>
                  <FAIcon name="comments" />
                </div>
              </div>
            </div>
          </div>

          {/* SUBSCRIPTION PLAN, CREDIT WALLET & LIMITS */}
          <div className="cc-card">
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon" style={{ background: "#eef2ff", color: "#4f46e5" }}>
                  <FAIcon name="wallet" />
                </div>
                <span>{canUseAI ? "Subscription & Credit Wallet" : "Subscription & Plan"}</span>
              </div>
            </div>

            <div style={{ marginBottom: "16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <Badge tone={loaderData.planTier === "PRO" ? "success" : "info"}>
                {`${loaderData.planTier} PLAN (${currentPlanConfig.billingInterval === "ONE_TIME" ? `$${currentPlanConfig.price} one-time` : `$${currentPlanConfig.price}/mo`})`}
              </Badge>
              <span style={{ fontSize: "11px", color: "#64748b", fontWeight: 500 }}>
                {canUseAI ? "API Platform Ledger" : "Shopify Platform"}
              </span>
            </div>

            {canUseAI ? (
              <>
                {/* TOTAL AVAILABLE CREDITS DISPLAY (ADDITIVE LEDGER BALANCE) */}
                <div style={{ padding: "14px", borderRadius: "10px", background: "linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%)", border: "1px solid #c7d2fe", marginBottom: "16px" }}>
                  <div style={{ fontSize: "11px", color: "#4338ca", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em" }}>Available Credit Balance</div>
                  <div style={{ fontSize: "26px", fontWeight: 800, color: "#1e1b4b", marginTop: "2px" }}>
                    {(loaderData.creditBalance?.availableBalance ?? (loaderData.monthlyLimit - loaderData.currentUsage)).toLocaleString()} Credits
                  </div>
                  <div style={{ fontSize: "12px", color: "#475569", marginTop: "4px", display: "flex", alignItems: "center", gap: "4px" }}>
                    <FAIcon name="circle-check" style={{ color: "#059669" }} />
                    <span>Additive balance (Unused credits preserved)</span>
                  </div>
                </div>

                {/* MONTHLY CYCLE USAGE METER */}
                <div style={{ marginBottom: "16px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.82rem", fontWeight: 600, color: "#334155" }}>
                    <span>Monthly Cycle Usage:</span>
                    <span>
                      {isUnlimitedPlan
                        ? `${loaderData.currentUsage} / Unlimited`
                        : `${loaderData.currentUsage} / ${loaderData.monthlyLimit}`}
                    </span>
                  </div>

                  <div className="cc-progress-track">
                    <div
                      className="cc-progress-fill"
                      style={{
                        width: `${usagePercentage}%`,
                        backgroundColor: usagePercentage >= 100 && !isUnlimitedPlan ? "#dc2626" : usagePercentage > 85 && !isUnlimitedPlan ? "#f59e0b" : "#4f46e5",
                      }}
                    />
                  </div>
                </div>

                {/* ACTIVE ALLOCATIONS BREAKDOWN */}
                {loaderData.creditBalance?.allocations && loaderData.creditBalance.allocations.length > 0 && (
                  <div style={{ marginBottom: "16px", padding: "10px", borderRadius: "8px", background: "#f8fafc", border: "1px solid #e2e8f0" }}>
                    <div style={{ fontSize: "11px", fontWeight: 700, color: "#475569", marginBottom: "6px" }}>Active Credit Allocations:</div>
                    <div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
                      {loaderData.creditBalance.allocations.map((a: any) => (
                        <div key={a.id} style={{ display: "flex", justifyContent: "space-between", fontSize: "11px", color: "#334155" }}>
                          <span>• {a.sourceType === "MONTHLY_PLAN" ? "Monthly Plan" : a.sourceType === "ADDITIONAL_PURCHASE" ? "Booster Package" : "Promo/Adjustment"}</span>
                          <strong style={{ color: "#059669" }}>+{a.creditsRemaining.toLocaleString()} remaining</strong>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* ACTION BUTTONS */}
                <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                  <button
                    type="button"
                    className="cc-btn cc-btn-primary cc-btn-block"
                    onClick={() => setShowPlansModal(true)}
                  >
                    <FAIcon name="rocket" />
                    Manage & Upgrade Plan
                  </button>
                </div>
              </>
            ) : (
              <>
                {/* INCLUDED PLAN FEATURES FOR STARTER & FREE */}
                <div style={{ padding: "14px", borderRadius: "10px", background: "#f8fafc", border: "1px solid #e2e8f0", marginBottom: "16px" }}>
                  <div style={{ fontSize: "11px", color: "#64748b", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "8px" }}>
                    Included in {currentPlanConfig.displayName}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                    {currentPlanConfig.features.map((f: string, idx: number) => (
                      <div key={idx} style={{ fontSize: "12px", color: "#334155", display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="check" size="xs" style={{ color: "#059669" }} />
                        <span>{f}</span>
                      </div>
                    ))}
                  </div>
                  {(() => {
                    const availableUpgradePlans = availablePlans.filter(
                      (p: any) => (p.planKey || p.name) !== loaderData.planTier
                    );
                    const topUpgradePlan = availableUpgradePlans.find(
                      (p: any) => (p.planKey || p.name) === "PRO" || p.aiUsageEnabled
                    ) || availableUpgradePlans[0];

                    if (!topUpgradePlan) return null;

                    return (
                      <div style={{ marginTop: "12px", paddingTop: "10px", borderTop: "1px dashed #cbd5e1", fontSize: "12px", color: "#4f46e5", display: "flex", alignItems: "center", gap: "6px" }}>
                        <FAIcon name="sparkles" />
                        <span>
                          Upgrade to {topUpgradePlan.displayName || "Pro"} for AI Assistant &amp; {topUpgradePlan.aiMonthlyLimit ? `${topUpgradePlan.aiMonthlyLimit.toLocaleString()} monthly credits.` : "advanced features."}
                        </span>
                      </div>
                    );
                  })()}
                </div>

                {/* ACTION BUTTONS FOR STARTER & FREE */}
                {(() => {
                  const availableUpgradePlans = availablePlans.filter(
                    (p: any) => (p.planKey || p.name) !== loaderData.planTier
                  );
                  const topUpgradePlan = availableUpgradePlans.find(
                    (p: any) => (p.planKey || p.name) === "PRO" || p.aiUsageEnabled
                  ) || availableUpgradePlans[0];
                  const upgradeBtnTitle = topUpgradePlan
                    ? `Upgrade to ${topUpgradePlan.displayName || topUpgradePlan.name || topUpgradePlan.planKey} Plan`
                    : "Upgrade to Pro Plan";

                  if (availableUpgradePlans.length === 0) return null;

                  return (
                    <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                      {topUpgradePlan && (
                        <button
                          type="button"
                          className="cc-btn cc-btn-primary cc-btn-block"
                          onClick={() => {
                            setSelectedCheckoutPlan(topUpgradePlan.planKey || topUpgradePlan.name);
                          }}
                        >
                          <FAIcon name="arrow-up" />
                          {upgradeBtnTitle}
                        </button>
                      )}
                      {/* SHOW 'View All Plans' ONLY WHEN MORE THAN 2 PLANS ARE ACTIVE */}
                      {availablePlans.length > 2 && (
                        <button
                          type="button"
                          className="cc-btn cc-btn-secondary cc-btn-block"
                          onClick={() => setShowPlansModal(true)}
                        >
                          <FAIcon name="rocket" />
                          View All Plans
                        </button>
                      )}
                    </div>
                  );
                })()}
              </>
            )}

            {/* QUICK INLINE PLAN SELECTOR ON THE CARD */}
            <div style={{ marginTop: "16px", paddingTop: "16px", borderTop: "1px solid #cbd5e1", display: "flex", flexDirection: "column", gap: "10px" }}>
              <div style={{ fontSize: "12px", fontWeight: 700, color: "#1e293b", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>Available Plans:</span>
                <span style={{ fontSize: "11px", color: "#64748b" }}>Click to select plan</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: `repeat(auto-fit, minmax(100px, 1fr))`, gap: "8px" }}>
                {availablePlans.map((cfg: any) => {
                  const p = cfg.planKey || cfg.name;
                  const isCurrent = loaderData.planTier === p;
                  const isOneTime = cfg.billingInterval === "ONE_TIME";
                  return (
                    <button
                      key={p}
                      type="button"
                      disabled={isCurrent}
                      style={{
                        padding: "10px 8px",
                        borderRadius: "8px",
                        border: isCurrent ? "2px solid #4f46e5" : "1px solid #cbd5e1",
                        background: isCurrent ? "#eef2ff" : "#ffffff",
                        textAlign: "left",
                        cursor: isCurrent ? "default" : "pointer",
                        opacity: isCurrent ? 0.7 : 1,
                        display: "flex",
                        flexDirection: "column",
                        gap: "2px",
                      }}
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        if (!isCurrent) {
                          setSelectedCheckoutPlan(p);
                        }
                      }}
                    >
                      <div style={{ fontWeight: 700, fontSize: "12px", color: "#0f172a", display: "flex", justifyContent: "space-between" }}>
                        <span>{cfg.displayName || cfg.name || p}</span>
                        {isCurrent && (
                          <span style={{ color: "#059669", fontSize: "10px", display: "inline-flex", alignItems: "center", gap: "3px" }}>
                            <FAIcon name="circle-check" size="xs" /> Active
                          </span>
                        )}
                      </div>
                      <div style={{ fontSize: "11px", color: "#059669", fontWeight: 700 }}>
                        ${cfg.price}{isOneTime ? " once" : "/mo"}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* SHOPIFY STORE CATALOG */}
          <div className="cc-card">
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon" style={{ background: "#ecfdf5", color: "#059669" }}>
                  <FAIcon name="store" />
                </div>
                <span>Shopify Store Catalog</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "0.75rem", color: "#059669", fontWeight: 600 }}>
                <FAIcon name="circle-check" /> Synced
              </div>
            </div>

            <Form method="post">
              <input type="hidden" name="shop" value={loaderData.shop} />
              <input type="hidden" name="_intent" value="sync_catalog" />
              <button type="submit" className="cc-btn cc-btn-secondary cc-btn-block">
                <FAIcon name="rotate" />
                Re-Sync Catalog
              </button>
            </Form>
          </div>

          {/* STORE BLOG POSTS & GUIDES */}
          <div className="cc-card" style={{ marginTop: "16px" }}>
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon" style={{ background: "#ecfdf5", color: "#059669" }}>
                  <FAIcon name="book-open" />
                </div>
                <span>Store Blog Posts &amp; Guides</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "0.75rem", color: "#059669", fontWeight: 600 }}>
                <FAIcon name="circle-check" /> Synced
              </div>
            </div>

            {loaderData.articles && loaderData.articles.length > 0 && (
              <div style={{ display: "flex", flexDirection: "column", gap: "8px", marginBottom: "14px", maxHeight: "160px", overflowY: "auto" }}>
                {loaderData.articles.map((art: any) => (
                  <div key={art.id} style={{ padding: "8px 10px", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: "8px", fontSize: "12px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginRight: "8px" }}>
                      <span style={{ fontWeight: 700, color: "#1e293b" }}>{art.title}</span>
                      <span style={{ color: "#64748b", marginLeft: "6px", fontSize: "11px" }}>({art.blogTitle || "Blog"})</span>
                    </div>
                    <a href={art.url || `/blogs/${art.blogHandle}/${art.handle}`} target="_blank" rel="noopener noreferrer" style={{ color: "#4f46e5", fontWeight: 600, fontSize: "11px", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: "3px" }}>
                      <span>View</span>
                      <FAIcon name="arrow-up-right-from-square" size="xs" />
                    </a>
                  </div>
                ))}
              </div>
            )}

            <Form method="post">
              <input type="hidden" name="shop" value={loaderData.shop} />
              <input type="hidden" name="_intent" value="sync_blogs" />
              <button type="submit" className="cc-btn cc-btn-secondary cc-btn-block">
                <FAIcon name="rotate" />
                Re-Sync Store Blogs
              </button>
            </Form>
          </div>

          {/* STORE HELPLINE & SUPPORT */}
          <div className="cc-card" style={{ marginTop: "16px" }}>
            <div className="cc-card-header">
              <div className="cc-card-title">
                <div className="cc-card-icon" style={{ background: "#eff6ff", color: "#2563eb" }}>
                  <FAIcon name="headset" />
                </div>
                <span>Store Helpline &amp; Support</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "0.75rem", color: "#2563eb", fontWeight: 600 }}>
                <FAIcon name="phone-volume" /> Live Desk
              </div>
            </div>

            <p style={{ fontSize: "0.85rem", color: "#475569", margin: "0 0 12px 0" }}>
              Official contact helpline and technical escalation desk for store assistance, order questions, and support.
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: "10px", marginBottom: "8px" }}>
              {(loaderData.activeHelplines && loaderData.activeHelplines.length > 0 ? loaderData.activeHelplines : [
                {
                  id: "default_hl",
                  department: "Customer Support Helpline",
                  phoneNumber: "+91 800-036-1445",
                  email: "ashvin@digihorizon.in",
                  hours: "24/7 Priority Support",
                  description: "Toll-free customer support helpline for orders and store queries.",
                }
              ]).map((hl: any) => (
                <div key={hl.id} style={{ padding: "12px", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: "8px", display: "flex", flexDirection: "column", gap: "6px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontWeight: 700, color: "#1e293b", fontSize: "12px" }}>{hl.department}</span>
                    <span style={{ fontSize: "10px", fontWeight: 600, padding: "2px 6px", borderRadius: "10px", background: "#dbeafe", color: "#1e40af" }}>
                      {hl.hours || "24/7 Support"}
                    </span>
                  </div>
                  {hl.description && (
                    <div style={{ fontSize: "11px", color: "#64748b" }}>{hl.description}</div>
                  )}
                  <div style={{ display: "flex", gap: "8px", marginTop: "4px", flexWrap: "wrap" }}>
                    {hl.phoneNumber && (
                      <a
                        href={`tel:${hl.phoneNumber.replace(/[^+\d]/g, "")}`}
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: "5px",
                          padding: "5px 10px",
                          background: "#ffffff",
                          border: "1px solid #cbd5e1",
                          borderRadius: "6px",
                          color: "#0f172a",
                          textDecoration: "none",
                          fontSize: "11px",
                          fontWeight: 600,
                        }}
                      >
                        <FAIcon name="phone" style={{ color: "#10b981", fontSize: "10px" }} />
                        <span>{hl.phoneNumber}</span>
                      </a>
                    )}
                    {hl.email && (
                      <a
                        href={`mailto:${hl.email}`}
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: "5px",
                          padding: "5px 10px",
                          background: "#ffffff",
                          border: "1px solid #cbd5e1",
                          borderRadius: "6px",
                          color: "#0f172a",
                          textDecoration: "none",
                          fontSize: "11px",
                          fontWeight: 600,
                        }}
                      >
                        <FAIcon name="envelope" style={{ color: "#6366f1", fontSize: "10px" }} />
                        <span>{hl.email}</span>
                      </a>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* PLAN SELECTION PRICING MODAL */}
      {showPlansModal && isMounted && typeof document !== "undefined" && createPortal(
        <div className="modal-overlay" style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100vw", height: "100vh", backgroundColor: "rgba(15, 23, 42, 0.65)", backdropFilter: "blur(4px)", zIndex: 99999, display: "flex", alignItems: "center", justifyContent: "center" }} onClick={(e) => { if (e.target === e.currentTarget) setShowPlansModal(false); }}>
          <div className="modal-card" style={{ maxWidth: "900px", width: "95%", backgroundColor: "#ffffff", borderRadius: "12px", padding: "24px", boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)", maxHeight: "90vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid #e2e8f0", paddingBottom: "12px" }}>
              <h3 style={{ fontSize: "18px", fontWeight: 700, margin: 0, color: "#0f172a" }}>Select a ShopPilot AI Subscription Plan</h3>
              <button type="button" onClick={() => setShowPlansModal(false)} style={{ background: "none", border: "none", fontSize: "16px", cursor: "pointer", color: "#64748b" }} title="Close">
                <FAIcon name="xmark" />
              </button>
            </div>

            <p style={{ fontSize: "13px", color: "#64748b", marginBottom: "20px" }}>
              Choose the best capacity plan for your storefront. Upgrades take effect immediately.
            </p>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: "16px" }}>
              {availablePlans.map((cfg: any) => {
                const p = cfg.planKey || cfg.name;
                const isCurrent = loaderData.planTier === p;
                const isOneTime = cfg.billingInterval === "ONE_TIME";

                return (
                  <div key={p} style={{ border: isCurrent ? "2px solid #4f46e5" : "1px solid #e2e8f0", borderRadius: "10px", padding: "16px", background: isCurrent ? "#eef2ff" : "#ffffff", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
                        <h4 style={{ fontSize: "16px", fontWeight: 700, margin: 0, color: "#1e293b" }}>{cfg.displayName || cfg.name || p}</h4>
                        {isCurrent && <span style={{ fontSize: "11px", fontWeight: 600, padding: "2px 8px", borderRadius: "12px", background: "#dcfce7", color: "#166534" }}>Current Plan</span>}
                      </div>
                      <div style={{ fontSize: "22px", fontWeight: 800, color: "#0f172a", marginBottom: "4px" }}>
                        ${cfg.price}<span style={{ fontSize: "12px", color: "#64748b", fontWeight: 400 }}>{isOneTime ? " one-time" : "/month"}</span>
                      </div>
                      <div style={{ fontSize: "12px", color: "#475569", fontWeight: 600, marginBottom: "8px" }}>
                        {cfg.aiMonthlyLimit ? `AI Quota: ${cfg.aiMonthlyLimit.toLocaleString()} msgs/mo` : "Shopify API Features"}
                      </div>
                      <p style={{ fontSize: "12px", color: "#64748b", marginBottom: "12px", lineHeight: 1.4 }}>{cfg.description}</p>
                      <ul style={{ paddingLeft: "16px", fontSize: "12px", color: "#334155", margin: "0 0 16px 0", lineHeight: 1.6 }}>
                        {(cfg.features || []).map((f: string, idx: number) => (
                          <li key={idx}>{f}</li>
                        ))}
                      </ul>
                    </div>

                    <button
                      type="button"
                      className={`cc-btn ${isCurrent ? "cc-btn-secondary" : "cc-btn-primary"} cc-btn-block`}
                      disabled={isCurrent}
                      onClick={() => {
                        setShowPlansModal(false);
                        setSelectedCheckoutPlan(p);
                      }}
                    >
                      {isCurrent ? "Active Plan" : isOneTime ? (cfg.price === 0 ? "Select Free Plan" : `Buy for $${cfg.price}`) : `Subscribe ($${cfg.price}/mo)`}
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* PAYMENT CHECKOUT & CONFIRMATION MODAL */}
      {selectedCheckoutPlan && isMounted && typeof document !== "undefined" && createPortal(
        <div className="modal-overlay" style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100vw", height: "100vh", backgroundColor: "rgba(15, 23, 42, 0.65)", backdropFilter: "blur(4px)", zIndex: 100000, display: "flex", alignItems: "center", justifyContent: "center" }} onClick={(e) => { if (e.target === e.currentTarget) setSelectedCheckoutPlan(null); }}>
          <div className="modal-card" style={{ maxWidth: "540px", width: "95%", backgroundColor: "#ffffff", borderRadius: "12px", padding: "24px", boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)", maxHeight: "90vh", overflowY: "auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid #e2e8f0", paddingBottom: "12px" }}>
              <h3 style={{ fontSize: "17px", fontWeight: 700, margin: 0, color: "#0f172a" }}>Checkout & Payment Method ({selectedCheckoutPlan} Plan)</h3>
              <button type="button" onClick={() => setSelectedCheckoutPlan(null)} style={{ background: "none", border: "none", fontSize: "16px", cursor: "pointer", color: "#64748b" }} title="Close">
                <FAIcon name="xmark" />
              </button>
            </div>

            <Form method="post" onSubmit={() => setSelectedCheckoutPlan(null)}>
              <input type="hidden" name="shop" value={loaderData.shop} />
              <input type="hidden" name="_intent" value="change_plan" />
              <input type="hidden" name="plan" value={selectedCheckoutPlan} />

              <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                <div style={{ padding: "12px", background: "#e0e7ff", borderRadius: "8px", fontSize: "13px", color: "#3730a3" }}>
                  Store Domain: <strong>{loaderData.shop}</strong>
                </div>

                {(() => {
                  const selectedPlanObj = (loaderData.plans && loaderData.plans[selectedCheckoutPlan]) || availablePlans.find((p: any) => (p.planKey || p.name) === selectedCheckoutPlan) || (PLAN_CONFIGS as any)[selectedCheckoutPlan];
                  const planDisplayName = selectedPlanObj?.displayName || selectedPlanObj?.name || selectedCheckoutPlan;
                  const isOneTime = selectedPlanObj?.billingInterval === "ONE_TIME" || selectedPlanObj?.billingType === "ONE_TIME";
                  const price = selectedPlanObj?.price ?? 0;
                  const aiMonthlyLimit = selectedPlanObj?.aiMonthlyLimit;

                  return (
                    <div style={{ border: "1px solid #e2e8f0", borderRadius: "8px", padding: "16px", background: "#f8fafc" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "8px" }}>
                        <span>Selected Plan:</span>
                        <strong>{planDisplayName} Plan</strong>
                      </div>
                      {aiMonthlyLimit ? (
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "8px" }}>
                          <span>Monthly AI Message Limit:</span>
                          <span>{aiMonthlyLimit.toLocaleString()} msgs</span>
                        </div>
                      ) : (
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "8px" }}>
                          <span>Features Included:</span>
                          <span>Shopify API & Storefront Features</span>
                        </div>
                      )}
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "8px" }}>
                        <span>Billing Interval:</span>
                        <span>{isOneTime ? "One-Time App Purchase" : "Every 30 Days (Monthly)"}</span>
                      </div>
                      <div style={{ borderTop: "1px solid #cbd5e1", paddingTop: "8px", marginTop: "8px", display: "flex", justifyContent: "space-between", fontSize: "14px", fontWeight: 700 }}>
                        <span>Total Amount Due:</span>
                        <span style={{ color: "#059669" }}>
                          ${price}.00 USD{isOneTime ? "" : "/mo"}
                        </span>
                      </div>
                    </div>
                  );
                })()}

                <input type="hidden" name="paymentMethod" value="card" />
                <input
                  type="hidden"
                  name="paymentAmount"
                  value={((loaderData.plans && loaderData.plans[selectedCheckoutPlan]) || availablePlans.find((p: any) => (p.planKey || p.name) === selectedCheckoutPlan) || (PLAN_CONFIGS as any)[selectedCheckoutPlan])?.price || 0}
                />

                {/* CREDIT OR DEBIT CARD DETAILS (ALWAYS DISPLAYED BY DEFAULT) */}
                <div style={{ border: "1px solid #cbd5e1", borderRadius: "8px", padding: "16px", background: "#ffffff", display: "flex", flexDirection: "column", gap: "12px" }}>
                  <div style={{ fontSize: "13px", fontWeight: 700, color: "#1e293b", display: "flex", alignItems: "center", gap: "8px" }}>
                    <FAIcon name="credit-card" style={{ color: "#4f46e5" }} />
                    <span>Credit or Debit Card Payment Details</span>
                  </div>

                  <div>
                    <label className="cc-label" style={{ fontSize: "12px", marginBottom: "4px" }}>Cardholder Name</label>
                    <input
                      type="text"
                      name="cardName"
                      className="cc-input"
                      placeholder="John Doe"
                      value={cardName}
                      onChange={(e) => setCardName(e.target.value)}
                      required
                    />
                  </div>

                  <div>
                    <label className="cc-label" style={{ fontSize: "12px", marginBottom: "4px" }}>Card Number</label>
                    <input
                      type="text"
                      name="cardNumber"
                      className="cc-input"
                      placeholder="4242 •••• •••• 4242"
                      value={cardNumber}
                      onChange={(e) => setCardNumber(e.target.value)}
                      required
                    />
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                    <div>
                      <label className="cc-label" style={{ fontSize: "12px", marginBottom: "4px" }}>Expiration (MM/YY)</label>
                      <input
                        type="text"
                        name="cardExpiry"
                        className="cc-input"
                        placeholder="12/28"
                        value={cardExpiry}
                        onChange={(e) => setCardExpiry(e.target.value)}
                        required
                      />
                    </div>
                    <div>
                      <label className="cc-label" style={{ fontSize: "12px", marginBottom: "4px" }}>CVC / CVV</label>
                      <input
                        type="password"
                        name="cardCvc"
                        className="cc-input"
                        placeholder="123"
                        maxLength={4}
                        value={cardCvc}
                        onChange={(e) => setCardCvc(e.target.value)}
                        required
                      />
                    </div>
                  </div>
                </div>

                <div style={{ display: "flex", gap: "12px", marginTop: "8px" }}>
                  <button type="button" className="cc-btn cc-btn-secondary" style={{ flex: 1 }} onClick={() => setSelectedCheckoutPlan(null)}>
                    Cancel
                  </button>
                  <button type="submit" className="cc-btn cc-btn-primary" style={{ flex: 1 }}>
                    Confirm & {loaderData.plans[selectedCheckoutPlan]?.billingInterval === "ONE_TIME" ? "Pay" : "Subscribe"} (${loaderData.plans[selectedCheckoutPlan]?.price}{loaderData.plans[selectedCheckoutPlan]?.billingInterval === "ONE_TIME" ? "" : "/mo"})
                  </button>
                </div>
              </div>
            </Form>
          </div>
        </div>,
        document.body
      )}

      {/* EDIT KNOWLEDGE BASE MODAL */}
      {editItem && (
        <Modal
          open={Boolean(editItem)}
          onClose={() => setEditItem(null)}
          title="Edit Knowledge Base Item"
          primaryAction={{
            content: "Save Changes",
            onAction: () => {
              const formEl = document.getElementById("edit-kb-form") as HTMLFormElement;
              if (formEl) formEl.requestSubmit();
            },
          }}
          secondaryActions={[
            {
              content: "Cancel",
              onAction: () => setEditItem(null),
            },
          ]}
        >
          <Modal.Section>
            <Form method="post" id="edit-kb-form" onSubmit={() => setEditItem(null)}>
              <input type="hidden" name="shop" value={loaderData.shop} />
              <input type="hidden" name="_intent" value="update_knowledge" />
              <input type="hidden" name="kId" value={editItem.id} />

              <BlockStack gap="400">
                <TextField
                  label="Title / Topic"
                  name="title"
                  value={editItem.title}
                  onChange={(val) => setEditItem({ ...editItem, title: val })}
                  autoComplete="off"
                />

                <Select
                  label="Category / Source Type"
                  name="sourceType"
                  options={[
                    { label: "FAQ / Question & Answer", value: "faq" },
                    { label: "Shipping Policy & Delivery Rates", value: "shipping" },
                    { label: "Return Policy & Refunds", value: "returns" },
                    { label: "General Terms & Store Policy", value: "policy" },
                  ]}
                  value={editItem.sourceType}
                  onChange={(val) => setEditItem({ ...editItem, sourceType: val })}
                />

                <TextField
                  label="Detailed Policy Content"
                  name="content"
                  value={editItem.content}
                  onChange={(val) => setEditItem({ ...editItem, content: val })}
                  multiline={4}
                  autoComplete="off"
                />
              </BlockStack>
            </Form>
          </Modal.Section>
        </Modal>
      )}

      {/* PLAN DETAILS DRAWER / MODAL */}
      {isMounted && selectedHistorySub && createPortal(
        <div className="modal-overlay" style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100vw", height: "100vh", backgroundColor: "rgba(15, 23, 42, 0.65)", backdropFilter: "blur(4px)", zIndex: 99999, display: "flex", alignItems: "center", justifyContent: "center" }} onClick={(e) => { if (e.target === e.currentTarget) setSelectedHistorySub(null); }}>
          <div className="modal-card" style={{ maxWidth: "540px", width: "95%", backgroundColor: "#ffffff", borderRadius: "12px", padding: "24px", boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid #e2e8f0", paddingBottom: "12px" }}>
              <h3 style={{ fontSize: "18px", fontWeight: 700, margin: 0, color: "#0f172a", display: "flex", alignItems: "center", gap: "8px" }}>
                <FAIcon name="crown" style={{ color: "#4f46e5" }} />
                {selectedHistorySub.plan} Plan Details
              </h3>
              <button type="button" onClick={() => setSelectedHistorySub(null)} style={{ background: "none", border: "none", fontSize: "16px", cursor: "pointer", color: "#64748b" }} title="Close">
                <FAIcon name="xmark" />
              </button>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                <span style={{ color: "#64748b" }}>Status:</span>
                <Badge tone={selectedHistorySub.status === "ACTIVE" ? "success" : selectedHistorySub.status === "REPLACED" ? "info" : "warning"}>
                  {selectedHistorySub.status}
                </Badge>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                <span style={{ color: "#64748b" }}>Price:</span>
                <strong style={{ color: "#1e293b" }}>${selectedHistorySub.price} / month ({selectedHistorySub.currency || "USD"})</strong>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                <span style={{ color: "#64748b" }}>Purchased Date:</span>
                <span>{new Date(selectedHistorySub.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</span>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                <span style={{ color: "#64748b" }}>Active Period:</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: "5px" }}>
                  <span>{new Date(selectedHistorySub.startedAt || selectedHistorySub.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</span>
                  <FAIcon name="arrow-right" size="xs" />
                  <span>{selectedHistorySub.endedAt ? new Date(selectedHistorySub.endedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" }) : new Date(selectedHistorySub.currentPeriodEnd).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</span>
                </span>
              </div>

              {selectedHistorySub.plan !== "FREE" && selectedHistorySub.plan !== "STARTER" && (
                <>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                    <span style={{ color: "#64748b" }}>Monthly Allocation:</span>
                    <strong>{selectedHistorySub.monthlyLimit.toLocaleString()} credits</strong>
                  </div>

                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                    <span style={{ color: "#64748b" }}>Credits Used:</span>
                    <span>{selectedHistorySub.currentUsage} credits</span>
                  </div>

                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px" }}>
                    <span style={{ color: "#64748b" }}>Credits Remaining:</span>
                    <span style={{ color: "#059669", fontWeight: 700 }}>{Math.max(0, selectedHistorySub.monthlyLimit - selectedHistorySub.currentUsage).toLocaleString()} credits</span>
                  </div>
                </>
              )}

              {selectedHistorySub.plan !== "FREE" && (
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", background: "#f8fafc", padding: "10px", borderRadius: "8px", border: "1px solid #e2e8f0" }}>
                  <span style={{ color: "#64748b" }}>Shopify Subscription ID:</span>
                  <code style={{ fontFamily: "monospace", fontSize: "11px", color: "#4f46e5" }}>{selectedHistorySub.shopifySubscriptionId || `gid://shopify/AppSubscription/${selectedHistorySub.id.slice(0, 8)}`}</code>
                </div>
              )}
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "20px" }}>
              <button type="button" className="cc-btn cc-btn-primary" onClick={() => setSelectedHistorySub(null)}>
                Close Details
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* PAYMENT RECEIPT MODAL */}
      {isMounted && selectedPaymentReceipt && createPortal(
        <div className="modal-overlay" style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100vw", height: "100vh", backgroundColor: "rgba(15, 23, 42, 0.65)", backdropFilter: "blur(4px)", zIndex: 99999, display: "flex", alignItems: "center", justifyContent: "center" }} onClick={(e) => { if (e.target === e.currentTarget) setSelectedPaymentReceipt(null); }}>
          <div className="modal-card" style={{ maxWidth: "500px", width: "95%", backgroundColor: "#ffffff", borderRadius: "12px", padding: "24px", boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px", borderBottom: "1px solid #e2e8f0", paddingBottom: "12px" }}>
              <h3 style={{ fontSize: "18px", fontWeight: 700, margin: 0, color: "#0f172a" }}>Payment Receipt</h3>
              <button type="button" onClick={() => setSelectedPaymentReceipt(null)} style={{ background: "none", border: "none", fontSize: "16px", cursor: "pointer", color: "#64748b" }} title="Close">
                <FAIcon name="xmark" />
              </button>
            </div>

            <div style={{ padding: "16px", borderRadius: "10px", background: "#eef2ff", border: "1px solid #c7d2fe", textAlign: "center", marginBottom: "16px" }}>
              <div style={{ fontSize: "11px", color: "#4f46e5", fontWeight: 700, textTransform: "uppercase" }}>Total Paid Amount</div>
              <div style={{ fontSize: "28px", fontWeight: 800, color: "#1e1b4b", marginTop: "2px" }}>
                ${selectedPaymentReceipt.amount.toFixed(2)} {selectedPaymentReceipt.currency || "USD"}
              </div>
              <Badge tone="success">{selectedPaymentReceipt.status}</Badge>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "10px", fontSize: "13px" }}>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ color: "#64748b" }}>Payment ID:</span>
                <code style={{ fontFamily: "monospace" }}>{selectedPaymentReceipt.id}</code>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ color: "#64748b" }}>Invoice Number:</span>
                <strong>{selectedPaymentReceipt.invoices?.[0]?.invoiceNumber || `INV-${selectedPaymentReceipt.id.slice(0, 6)}`}</strong>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ color: "#64748b" }}>Payment Date:</span>
                <span>{new Date(selectedPaymentReceipt.paidAt || selectedPaymentReceipt.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</span>
              </div>
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "20px" }}>
              <button type="button" className="cc-btn cc-btn-primary" onClick={() => setSelectedPaymentReceipt(null)}>
                Close Receipt
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
}

export function ErrorBoundary() {
  const error: any = useRouteError();
  console.error("[ShopPilot AI App ErrorBoundary]:", error);
  const errorMessage = error?.message || error?.data?.message || (typeof error === "string" ? error : "A temporary session error occurred.");

  return (
    <div style={{ padding: "40px", textAlign: "center", fontFamily: "sans-serif", backgroundColor: "#f8fafc", minHeight: "100vh" }}>
      <div style={{ maxWidth: "480px", margin: "40px auto", backgroundColor: "#ffffff", padding: "32px", borderRadius: "12px", boxShadow: "0 10px 15px -3px rgba(0,0,0,0.1)" }}>
        <h2 style={{ color: "#0f172a", fontSize: "20px", fontWeight: 700, marginBottom: "8px" }}>ShopPilot AI Control Panel</h2>
        <p style={{ color: "#dc2626", margin: "12px 0 20px 0", fontSize: "14px", lineHeight: 1.5 }}>
          {errorMessage}
        </p>
        <a href="/app" style={{ display: "inline-block", padding: "10px 20px", backgroundColor: "#4f46e5", color: "#ffffff", borderRadius: "8px", textDecoration: "none", fontWeight: 600, fontSize: "13px" }}>
          Reload Control Panel
        </a>
      </div>
    </div>
  );
}
