import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, Form, useActionData, useSubmit, useNavigation, useRouteError, useNavigate } 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 { BillingService } from "../services/billing.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, maskApiKey, type AIModelDefinition, type AIProviderDefinition } from "../services/ai-config.server";
import { encryptToken } from "../lib/security/encryption";
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 planInfo = await BillingService.getActiveSubscription(shop.shopifyDomain);

    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 { cleanupLegacyDummyData } = await import("../services/article.server");
    await cleanupLegacyDummyData(shop.id);

    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: 20,
    }).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 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 { StoreIntelligenceService } = await import("../services/store-intelligence.server");
    const storeProfile = await StoreIntelligenceService.getStoreProfile(shop.id, shop.shopifyDomain).catch(() => null);
    const themeContext = await StoreIntelligenceService.getThemeContext(shop.id, shop.shopifyDomain).catch(() => null);

    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,
      storeProfile,
      themeContext,
      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",
      openaiApiKeyMasked: maskApiKey(settings?.openaiApiKey),
      geminiApiKeyMasked: maskApiKey(settings?.geminiApiKey),
      temperature: settings?.temperature ?? 0.7,
      position: settings?.position || "bottom-right",
      isEnabled,
      isChatbotAdminDisabled,
      planTier: planInfo.plan,
      planInfo,
      pricingPlansUrl: planInfo.pricingPlansUrl,
      billingSummary,
      conversationCount,
      productCount,
      articleCount,
      articles: storeArticles.map((a) => {
        const rawUrl = a.url || `/blogs/${a.blogHandle || 'news'}/${a.handle}`;
        const absoluteUrl = rawUrl.startsWith("http") ? rawUrl : `https://${shop.shopifyDomain}${rawUrl.startsWith("/") ? "" : "/"}${rawUrl}`;
        return {
          id: a.id,
          shopifyArticleId: a.shopifyArticleId,
          blogHandle: a.blogHandle,
          blogTitle: a.blogTitle,
          title: a.title,
          handle: a.handle,
          summary: a.summary,
          url: absoluteUrl,
          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: [],
      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="ShopPilot_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") || "");

      // --- Server-side Validation ---
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (storeSupportEmail && !emailRegex.test(storeSupportEmail)) {
        return { success: false, error: "Please enter a valid support email address (e.g. support@yourstore.com)." };
      }
      const phoneRegex = /^\+?[\d\s\-().]{7,25}$/;
      if (storeSupportPhone && !phoneRegex.test(storeSupportPhone)) {
        return { success: false, error: "Please enter a valid phone number (e.g. +1 555 234 5678)." };
      }
      const urlRegex = /^(https?:\/\/|\/|#)/;
      if (storeContactUrl && !urlRegex.test(storeContactUrl)) {
        return { success: false, error: "Contact URL must start with http://, https://, or /." };
      }
      if (shippingPolicyUrl && !urlRegex.test(shippingPolicyUrl)) {
        return { success: false, error: "Shipping Policy URL must start with http://, https://, or /." };
      }
      if (disclaimerUrl && !urlRegex.test(disclaimerUrl)) {
        return { success: false, error: "Disclaimer URL must start with http://, https://, or /." };
      }
      if (!botName.trim()) {
        return { success: false, error: "Bot name is required." };
      }
      // --- End Validation ---

      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 canUseAI = canUseFeature(planTier, "openai");
      const aiProvider = canUseAI ? String(formData.get("aiProvider") || "openai") : "openai";
      const submittedModel = String(formData.get("model") || (aiProvider === "gemini" ? "gemini-1.5-flash" : "gpt-4o-mini"));

      const rawOpenaiKey = formData.get("openaiApiKey");
      const rawGeminiKey = formData.get("geminiApiKey");
      const keyUpdateData: any = {};

      if (canUseAI) {
        if (rawOpenaiKey !== null) {
          const k = String(rawOpenaiKey).trim();
          if (k.length > 0 && !k.startsWith("••••")) {
            keyUpdateData.openaiApiKey = encryptToken(k);
          }
        }
        if (rawGeminiKey !== null) {
          const k = String(rawGeminiKey).trim();
          if (k.length > 0 && !k.startsWith("••••")) {
            keyUpdateData.geminiApiKey = encryptToken(k);
          }
        }
      }

      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 } : {}),
          ...keyUpdateData,
        },
        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",
          ...keyUpdateData,
        },
      });

      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: "Settings saved successfully!",
        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, syncStorePagesAndPolicies } = await import("../services/article.server");
      const res = await syncStoreArticles(shopDomain);
      const extra = await syncStorePagesAndPolicies(shopDomain);
      const parts = [];
      if (res.syncedCount > 0) parts.push(`${res.syncedCount} blog articles`);
      if (extra.pagesCount > 0) parts.push(`${extra.pagesCount} pages`);
      if (extra.policiesCount > 0) parts.push(`${extra.policiesCount} legal policies`);
      const summary = parts.length > 0 ? parts.join(", ") : "0 items (none found on store)";
      return { success: true, message: `Successfully synchronized ${summary} from Shopify store!` };
    }

    if (intent === "change_plan") {
      const pricingUrl = BillingService.getPricingUrl(shopDomain);
      return {
        success: true,
        message: "Redirecting to Shopify Pricing Plans selection...",
        confirmationUrl: pricingUrl,
      };
    }

    if (intent === "reanalyze_store") {
      const { StoreIntelligenceService } = await import("../services/store-intelligence.server");
      const result = await StoreIntelligenceService.analyzeStoreAndBuildProfile(shop.id, shop.shopifyDomain);
      return {
        success: true,
        message: `Store intelligence successfully re-analyzed! Category: ${result.profile.category.toUpperCase()} (${Math.round(result.profile.categoryConfidence * 100)}% match).`,
      };
    }

    if (intent === "purchase_credits") {
      return {
        success: false,
        error: "Message credits are not required. Store owners bring their own OpenAI/Gemini API keys.",
      };
    }

    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 navigate = useNavigate();

  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 starterPlan = availablePlans.find((p: any) => String(p.planKey || p.name || "").toUpperCase() === "STARTER");
  const proPlan = availablePlans.find((p: any) => String(p.planKey || p.name || "").toUpperCase() === "PRO");
  const isStarterActive = Boolean(starterPlan && starterPlan.isActive !== false);
  const isProActive = Boolean(proPlan && proPlan.isActive !== false);
  const hasPaidPlansActive = isStarterActive || isProActive;

  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);
  const [openaiApiKey, setOpenaiApiKey] = useState(loaderData.openaiApiKeyMasked || "");
  const [geminiApiKey, setGeminiApiKey] = useState(loaderData.geminiApiKeyMasked || "");

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

  // Client-side form validation errors
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // 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 History & Receipt Modal States
  const [selectedHistorySub, setSelectedHistorySub] = useState<any | null>(null);
  const [selectedPaymentReceipt, setSelectedPaymentReceipt] = useState<any | null>(null);

  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 handleSettingsSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    const errors: Record<string, string> = {};
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^\+?[\d\s\-().]{7,25}$/;
    const urlRegex = /^(https?:\/\/|\/|#)/;

    if (!botName.trim()) {
      errors.botName = "Bot name is required.";
    }
    if (storeSupportEmail && !emailRegex.test(storeSupportEmail)) {
      errors.storeSupportEmail = "Please enter a valid email address.";
    }
    if (storeSupportPhone && !phoneRegex.test(storeSupportPhone)) {
      errors.storeSupportPhone = "Please enter a valid phone number (e.g. +1 555 234 5678).";
    }
    if (storeContactUrl && !urlRegex.test(storeContactUrl)) {
      errors.storeContactUrl = "Must start with http://, https://, or /.";
    }
    if (shippingPolicyUrl && !urlRegex.test(shippingPolicyUrl)) {
      errors.shippingPolicyUrl = "Must start with http://, https://, or /.";
    }
    if (disclaimerUrl && !urlRegex.test(disclaimerUrl)) {
      errors.disclaimerUrl = "Must start with http://, https://, or /.";
    }

    setFormErrors(errors);
    if (Object.keys(errors).length > 0) {
      e.preventDefault();
    }
  };

  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>
          <Form method="post" onSubmit={handleSettingsSubmit}>
            <input type="hidden" name="shop" value={loaderData.shop} />
            <input type="hidden" name="_intent" value="save_ai_settings" />



            {/* AI ENGINE & BYOK API KEY 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 & BYOK API Key Configuration</span>
                  </div>
                  <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
                    <Badge tone="success">PRO PLAN ACTIVE</Badge>
                    <Badge tone={aiProvider === "gemini" ? "attention" : "info"}>
                      {selectedProviderDetail.badge}
                    </Badge>
                  </div>
                </div>

                <p className="cc-body-text" style={{ marginTop: 0, marginBottom: "20px" }}>
                  Connect your store's own OpenAI or Google Gemini API keys. You maintain full ownership of your API keys with no artificial message quotas or extra usage fees imposed by our app.
                </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">Selected provider: {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>

                {/* API KEY INPUTS (BYOK) */}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "20px" }}>
                  <div>
                    <label className="cc-label">OpenAI API Key (sk-...)</label>
                    <input
                      type="password"
                      name="openaiApiKey"
                      className="cc-input"
                      value={openaiApiKey}
                      onChange={(e) => setOpenaiApiKey(e.target.value)}
                      placeholder={loaderData.openaiApiKeyMasked || "sk-proj-..."}
                      autoComplete="off"
                    />
                    <div className="cc-subtext">
                      {loaderData.openaiApiKeyMasked ? `Saved & Encrypted: ${loaderData.openaiApiKeyMasked}` : "Enter your OpenAI secret key"}
                    </div>
                  </div>

                  <div>
                    <label className="cc-label">Google Gemini API Key (AIza...)</label>
                    <input
                      type="password"
                      name="geminiApiKey"
                      className="cc-input"
                      value={geminiApiKey}
                      onChange={(e) => setGeminiApiKey(e.target.value)}
                      placeholder={loaderData.geminiApiKeyMasked || "AIzaSy..."}
                      autoComplete="off"
                    />
                    <div className="cc-subtext">
                      {loaderData.geminiApiKeyMasked ? `Saved & Encrypted: ${loaderData.geminiApiKeyMasked}` : "Enter your Google Gemini API key"}
                    </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>
            ) : (
              <div className="cc-card" style={{ borderLeft: "4px solid #4F46E5", padding: "20px" }}>
                <div className="cc-card-header">
                  <div className="cc-card-title">
                    <div className="cc-card-icon">
                      <FAIcon name="lock" style={{ color: "#4F46E5" }} />
                    </div>
                    <span>AI Engine & BYOK Configuration</span>
                  </div>
                  <Badge tone="info">PRO PLAN EXCLUSIVE</Badge>
                </div>
                <p className="cc-body-text" style={{ marginTop: "8px", marginBottom: "16px" }}>
                  AI features (conversational sales assistant, smart recommendations, customer support, OpenAI & Gemini key integration) are available on the Pro plan.
                </p>
                <div>
                  {isProActive ? (
                    <Button
                      variant="primary"
                      onClick={() => {
                        const search = window.location.search || `?shop=${loaderData.shop}`;
                        navigate(`/app/billing${search}`);
                      }}
                    >
                      Upgrade to {proPlan?.displayName || "Pro"} (${proPlan?.price ?? 79}/mo)
                    </Button>
                  ) : (
                    <div style={{ display: "inline-flex", alignItems: "center", gap: "8px", flexWrap: "wrap" }}>
                      <Badge tone="warning">Pro Plan Pending Shopify Review</Badge>
                      <span style={{ fontSize: "12px", color: "#64748b" }}>
                        Will be enabled once the app review is approved and published.
                      </span>
                    </div>
                  )}
                </div>
                <input type="hidden" name="aiProvider" value={aiProvider} />
                <input type="hidden" name="model" value={model} />
              </div>
            )}

            {/* 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>
                        {formErrors.botName && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.botName}</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 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 &amp; order questions.</div>
                        {formErrors.storeSupportEmail && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.storeSupportEmail}</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>
                        {formErrors.storeSupportPhone && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.storeSupportPhone}</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>
                        {formErrors.storeContactUrl && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.storeContactUrl}</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>
                        {formErrors.shippingPolicyUrl && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.shippingPolicyUrl}</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>
                        {formErrors.disclaimerUrl && <div style={{ color: "#dc2626", fontSize: "12px", marginTop: "4px" }}>{formErrors.disclaimerUrl}</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 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"
                            onClick={() => {
                              const search = window.location.search || `?shop=${loaderData.shop}`;
                              navigate(`/app/billing${search}`);
                            }}
                            className="cc-btn cc-btn-secondary"
                            style={{ fontSize: "11px", padding: "4px 8px", display: "inline-flex", alignItems: "center", gap: "5px", textDecoration: "none", cursor: "pointer", border: "1px solid #e2e8f0", borderRadius: "6px", background: "#f8fafc" }}
                          >
                            <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 (SHOPIFY-AUTHORITATIVE) */}
          <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>Subscription &amp; Plan</span>
              </div>
            </div>

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

            {/* INCLUDED PLAN FEATURES */}
            <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 || loaderData.planTier} Plan
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                {(currentPlanConfig.features && currentPlanConfig.features.length > 0 ? currentPlanConfig.features : (PLAN_CONFIGS[loaderData.planTier as PlanTier]?.features || ["Shopify Catalog Search & Querying", "Product details & specifications"])).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>
            </div>

            {/* AUTHORITATIVE ACTION BUTTONS */}
            <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
              {loaderData.planTier === "FREE" && (
                <>
                  {hasPaidPlansActive ? (
                    <button
                      type="button"
                      onClick={() => {
                        const search = window.location.search || `?shop=${loaderData.shop}`;
                        navigate(`/app/billing${search}`);
                      }}
                      className="cc-btn cc-btn-primary cc-btn-block"
                      style={{ textDecoration: "none", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px", background: "#4338ca", border: "none", cursor: "pointer", padding: "10px 16px", borderRadius: "8px", color: "#fff", fontWeight: 600, width: "100%" }}
                    >
                      <FAIcon name="wand-magic-sparkles" />
                      View Plans & Upgrade
                    </button>
                  ) : (
                    <div style={{ padding: "10px 14px", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: "8px", fontSize: "12px", color: "#64748b", textAlign: "center" }}>
                      <span>Free Plan Active • Paid tiers unlock following Shopify review approval</span>
                    </div>
                  )}
                </>
              )}

              {loaderData.planTier === "STARTER" && (
                <>
                  <div style={{ padding: "8px 12px", background: "#ecfdf5", border: "1px solid #a7f3d0", borderRadius: "8px", fontSize: "12px", color: "#065f46", fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                    <FAIcon name="circle-check" />
                    <span>Current Plan: {starterPlan?.displayName || "Starter"}</span>
                  </div>
                  {isProActive && (
                    <button
                      type="button"
                      onClick={() => {
                        const search = window.location.search || `?shop=${loaderData.shop}`;
                        navigate(`/app/billing${search}`);
                      }}
                      className="cc-btn cc-btn-primary cc-btn-block"
                      style={{ textDecoration: "none", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px", background: "#4338ca", border: "none", cursor: "pointer", padding: "10px 16px", borderRadius: "8px", color: "#fff", fontWeight: 600, width: "100%" }}
                    >
                      <FAIcon name="wand-magic-sparkles" />
                      Upgrade to {proPlan?.displayName || "Pro"}
                    </button>
                  )}

                  <button
                    type="button"
                    onClick={() => {
                      const search = window.location.search || `?shop=${loaderData.shop}`;
                      navigate(`/app/billing${search}`);
                    }}
                    className="cc-btn cc-btn-secondary cc-btn-block"
                    style={{ textDecoration: "none", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px", background: "#f8fafc", border: "1px solid #cbd5e1", cursor: "pointer", padding: "10px 16px", borderRadius: "8px", color: "#334155", fontWeight: 600, width: "100%" }}
                  >
                    <FAIcon name="rotate-left" />
                    Change / Revert Plan
                  </button>
                </>
              )}

              {loaderData.planTier === "PRO" && (
                <>
                  <div style={{ padding: "8px 12px", background: "#ecfdf5", border: "1px solid #a7f3d0", borderRadius: "8px", fontSize: "12px", color: "#065f46", fontWeight: 600, display: "flex", alignItems: "center", gap: "6px" }}>
                    <FAIcon name="circle-check" />
                    <span>Current Plan: {proPlan?.displayName || "Pro"}</span>
                  </div>
                  <button
                    type="button"
                    onClick={() => {
                      const search = window.location.search || `?shop=${loaderData.shop}`;
                      navigate(`/app/billing${search}`);
                    }}
                    className="cc-btn cc-btn-secondary cc-btn-block"
                    style={{ textDecoration: "none", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px", background: "#f8fafc", border: "1px solid #cbd5e1", cursor: "pointer", padding: "10px 16px", borderRadius: "8px", color: "#334155", fontWeight: 600, width: "100%" }}
                  >
                    <FAIcon name="rotate-left" />
                    Change / Revert Plan
                  </button>
                </>
              )}
            </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: (loaderData.articles && loaderData.articles.length > 0) ? "#059669" : "#64748b", fontWeight: 600 }}>
                <FAIcon name={(loaderData.articles && loaderData.articles.length > 0) ? "circle-check" : "circle-info"} />
                {(loaderData.articles && loaderData.articles.length > 0) ? `Synced (${loaderData.articles.length})` : "0 Synced"}
              </div>
            </div>

            {loaderData.articles && loaderData.articles.length > 0 ? (
              <div style={{ display: "flex", flexDirection: "column", gap: "8px", marginBottom: "14px", maxHeight: "180px", overflowY: "auto" }}>
                {loaderData.articles.map((art: any) => {
                  const viewUrl = art.url || `https://${loaderData.shop}/blogs/${art.blogHandle || 'news'}/${art.handle}`;
                  return (
                    <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={viewUrl} target="_blank" rel="noopener noreferrer" style={{ color: "#4f46e5", fontWeight: 600, fontSize: "11px", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: "3px", flexShrink: 0 }}>
                        <span>View</span>
                        <FAIcon name="arrow-up-right-from-square" size="xs" />
                      </a>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div style={{ padding: "12px", background: "#f8fafc", border: "1px dashed #cbd5e1", borderRadius: "8px", fontSize: "12px", color: "#64748b", textAlign: "center", marginBottom: "14px" }}>
                <FAIcon name="circle-info" style={{ marginRight: "6px", color: "#94a3b8" }} />
                No blog posts found in your Shopify store. To add posts, go to <strong>Shopify Admin &gt; Content &gt; Blog posts</strong>, then click <strong>Re-Sync Store Blogs</strong>.
              </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 8000361445",
                  email: "ashvin@digihorizon.in",
                  hours: "24/7 Priority Support",
                  description: "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>

      {/* 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>
  );
}
