"use client";
import {
  Page,
  Card,
  FormLayout,
  TextField,
  Select,
  Button,
  ButtonGroup,
  Text,
  InlineStack,
  BlockStack,
  Banner,
  Checkbox,
  Grid,
  LegacyCard,
  Combobox,
  Listbox,
  Tag,
  Autocomplete,
  Spinner,
  Thumbnail,
  Badge,
  ChoiceList,
} from '@shopify/polaris';
import { FolderIcon } from '@shopify/polaris-icons';
import { useState, useCallback, useMemo, useEffect } from 'react';
import { useNavigate, useSearchParams } from '@remix-run/react';
import { extractVariablesFromWhatsAppMessage } from '../utils/whatsappMessagePreview';
import {
  getAllTemplateListForAbandonedCart,
  getAllTemplateListForOrderConfirmation,
  getAllTemplateListForOrderStatus,
  getAllTemplateListForReEngage,
  getSelectedTemplatebyName,
  saveTemporaryFile
} from '../utils/templateApi';
import { fetchTriggerById, updateTrigger } from '../utils/abandonedCartApi';
import { fetchallCategoryList } from '../utils/productApi';
import { userDataReady, getAutoReplyToken, getAPIToken, getUserInfo, getAccountDetails } from '../utils/apiConfig';
import WhatsAppPreview from '../components/WhatsAppPreview';

// --- helpers ---

const CATEGORY_CONFIG = {
  1: { label: 'Abandoned Cart', backPath: '/app/auto-triggers/abandoned-cart', hasCollections: true, hasTriggerTypeSelect: false, isReEngage: false },
  2: { label: 'Order Confirmation', backPath: '/app/auto-triggers/order-confirmation', hasCollections: false, hasTriggerTypeSelect: false, isReEngage: false },
  4: { label: 'Order Status (Shipped / Order Picked Up)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  5: { label: 'Order Status (Out for Delivery)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  6: { label: 'Order Status (Delivered)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  7: { label: 'Order Status (Cancelled)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  8: { label: 'Order Status (Fulfilled)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  22: { label: 'Order Status (Order delay)', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  23: { label: 'Order Status (Delivery Failed (shopify))', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  25: { label: 'Order Status (Return Picked up (shopify))', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  19: { label: 'Order Status (Ready to ship (shopify))', backPath: '/app/auto-triggers/order-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  9: { label: 'Payment Pending', backPath: '/app/auto-triggers/payment-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  10: { label: 'Refunded', backPath: '/app/auto-triggers/payment-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  12: { label: 'Paid', backPath: '/app/auto-triggers/payment-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
  11: { label: 'Win-Back', backPath: '/app/auto-triggers/re-engage', hasCollections: false, hasTriggerTypeSelect: false, isReEngage: true },
  14: { label: 'Partially Paid', backPath: '/app/auto-triggers/payment-status', hasCollections: false, hasTriggerTypeSelect: true, isReEngage: false },
};

const ORDER_STATUS_TYPE_OPTIONS = [
  { label: 'Shipped / Order Picked Up', value: '4' },
  { label: 'Out for Delivery', value: '5' },
  { label: 'Delivered', value: '6' },
  { label: 'Cancelled', value: '7' },
  { label: 'Fulfilled', value: '8' },
  { label: 'Order delay', value: '22' },
  { label: 'Delivery Failed (shopify)', value: '23' },
  { label: 'Return Picked up (shopify)', value: '25' },
  { label: 'Ready to ship (shopify)', value: '19' },
];

const PAYMENT_STATUS_TYPE_OPTIONS = [
  { label: 'Payment Pending', value: '9' },
  { label: 'Refunded', value: '10' },
  { label: 'Paid', value: '12' },
  { label: 'Partially Paid', value: '14' },
];

const AVAILABLE_VARIABLES_BY_CATEGORY = {
  1: [
    { label: 'cart_last_id', value: 'cart_last_id' },
    { label: 'cart_created_at', value: 'cart_created_at' },
    { label: 'cart_completed_at', value: 'cart_completed_at' },
    { label: 'cart_total_price', value: 'cart_total_price' },
    { label: 'cart_currency', value: 'cart_currency' },
    { label: 'cart_customer_id', value: 'cart_customer_id' },
    { label: 'customer_first_name', value: 'customer_first_name' },
    { label: 'customer_last_name', value: 'customer_last_name' },
    { label: 'customer_email', value: 'customer_email' },
    { label: 'customer_phone', value: 'customer_phone' },
    { label: 'number_of_orders', value: 'number_of_orders' },
    { label: 'customer_duration', value: 'customer_duration' },
    { label: 'customer_image', value: 'customer_image' },
    { label: 'customer_address', value: 'customer_address' },
    { label: 'line_item_id', value: 'line_item_id' },
    { label: 'line_item_title', value: 'line_item_title' },
    { label: 'line_item_quantity', value: 'line_item_quantity' },
    { label: 'line_item_variant', value: 'line_item_variant' },
    { label: 'line_item_variant_image', value: 'line_item_variant_image' },
    { label: 'checkout_url', value: 'checkout_url' },
    { label: 'abandoned_checkout_url', value: 'abandoned_checkout_url' },
    { label: 'shipping_address', value: 'shipping_address' },
    { label: 'billing_address', value: 'billing_address' },
    { label: 'support_email', value: 'support_email' },
    { label: 'support_phone', value: 'support_phone' },
  ],
  2: [
    { label: 'order_id', value: 'order_id' },
    { label: 'order_name', value: 'order_name' },
    { label: 'order_date', value: 'order_date' },
    { label: 'order_total_price', value: 'order_total_price' },
    { label: 'order_currency', value: 'order_currency' },
    { label: 'payment_status', value: 'payment_status' },
    { label: 'fulfillment_status', value: 'fulfillment_status' },
    { label: 'confirmation_status', value: 'confirmation_status' },
    { label: 'confirmation_number', value: 'confirmation_number' },
    { label: 'order_number', value: 'order_number' },
    { label: 'order_status_url', value: 'order_status_url' },
    { label: 'customer_id', value: 'customer_id' },
    { label: 'first_name', value: 'first_name' },
    { label: 'last_name', value: 'last_name' },
    { label: 'email', value: 'email' },
    { label: 'phone', value: 'phone' },
    { label: 'default_address', value: 'default_address' },
    { label: 'billing_address', value: 'billing_address' },
    { label: 'shipping_address', value: 'shipping_address' },
    { label: 'shipping_method', value: 'shipping_method' },
    { label: 'shipping_price', value: 'shipping_price' },
    { label: 'tracking_number', value: 'tracking_number' },
    { label: 'tracking_url', value: 'tracking_url' },
    { label: 'item_id', value: 'item_id' },
    { label: 'item_title', value: 'item_title' },
    { label: 'item_quantity', value: 'item_quantity' },
    { label: 'item_price', value: 'item_price' },
    { label: 'item_variant_title', value: 'item_variant_title' },
    { label: 'item_variant_image', value: 'item_variant_image' },
    { label: 'subtotal', value: 'subtotal' },
    { label: 'total_discounts', value: 'total_discounts' },
    { label: 'total_tax', value: 'total_tax' },
  ],
  orderStatus: [
    { label: 'first_name', value: 'first_name' },
    { label: 'last_name', value: 'last_name' },
    { label: 'order_name', value: 'order_name' },
    { label: 'email', value: 'email' },
    { label: 'phone', value: 'phone' },
    { label: 'order_id', value: 'order_id' },
    { label: 'shipment_id', value: 'shipment_id' },
    { label: 'shipping_address', value: 'shipping_address' },
    { label: 'awb', value: 'awb' },
    { label: 'status', value: 'status' },
    { label: 'status_code', value: 'status_code' },
    { label: 'current_status', value: 'current_status' },
    { label: 'current_timestamp', value: 'current_timestamp' },
    { label: 'etd', value: 'etd' },
    { label: 'courier_name', value: 'courier_name' },
    { label: 'pickup_date', value: 'pickup_date' },
    { label: 'scan_date', value: 'scan_date' },
    { label: 'scan_location', value: 'scan_location' },
    { label: 'scan_activity', value: 'scan_activity' },
    { label: 'order_date', value: 'order_date' },
    { label: 'order_total_price', value: 'order_total_price' },
    { label: 'order_currency', value: 'order_currency' },
    { label: 'payment_status', value: 'payment_status' },
    { label: 'fulfillment_status', value: 'fulfillment_status' },
    { label: 'tracking_number', value: 'tracking_number' },
    { label: 'tracking_url', value: 'tracking_url' },
    { label: 'item_id', value: 'item_id' },
    { label: 'item_title', value: 'item_title' },
    { label: 'item_quantity', value: 'item_quantity' },
    { label: 'item_price', value: 'item_price' },
    { label: 'subtotal', value: 'subtotal' },
    { label: 'total_discounts', value: 'total_discounts' },
    { label: 'total_tax', value: 'total_tax' },
  ],
  paymentStatus: [
    { label: 'order_id', value: 'order_id' },
    { label: 'order_name', value: 'order_name' },
    { label: 'order_date', value: 'order_date' },
    { label: 'order_total_price', value: 'order_total_price' },
    { label: 'order_currency', value: 'order_currency' },
    { label: 'payment_status', value: 'payment_status' },
    { label: 'fulfillment_status', value: 'fulfillment_status' },
    { label: 'confirmation_status', value: 'confirmation_status' },
    { label: 'confirmation_number', value: 'confirmation_number' },
    { label: 'customer_id', value: 'customer_id' },
    { label: 'first_name', value: 'first_name' },
    { label: 'last_name', value: 'last_name' },
    { label: 'email', value: 'email' },
    { label: 'phone', value: 'phone' },
    { label: 'default_address', value: 'default_address' },
    { label: 'billing_address', value: 'billing_address' },
    { label: 'shipping_method', value: 'shipping_method' },
    { label: 'shipping_price', value: 'shipping_price' },
    { label: 'tracking_number', value: 'tracking_number' },
    { label: 'tracking_url', value: 'tracking_url' },
    { label: 'item_id', value: 'item_id' },
    { label: 'item_title', value: 'item_title' },
    { label: 'item_quantity', value: 'item_quantity' },
    { label: 'item_price', value: 'item_price' },
    { label: 'subtotal', value: 'subtotal' },
    { label: 'total_discounts', value: 'total_discounts' },
    { label: 'total_tax', value: 'total_tax' },
    { label: 'refund_id', value: 'refund_id' },
    { label: 'refund_note', value: 'refund_note' },
    { label: 'refund_amount', value: 'refund_amount' },
    { label: 'refund_currency', value: 'refund_currency' },
  ],
  12: [
    { label: 'order_id', value: 'order_id' },
    { label: 'order_number', value: 'order_number' },
    { label: 'order_name', value: 'order_name' },
    { label: 'confirmation_number', value: 'confirmation_number' },
    { label: 'order_date', value: 'order_date' },
    { label: 'order_status_url', value: 'order_status_url' },
    { label: 'order_currency', value: 'order_currency' },
    { label: 'order_financial_status', value: 'order_financial_status' },
    { label: 'order_total_price', value: 'order_total_price' },
    { label: 'order_subtotal_price', value: 'order_subtotal_price' },
    { label: 'order_total_tax', value: 'order_total_tax' },
    { label: 'order_total_discounts', value: 'order_total_discounts' },
    { label: 'order_outstanding', value: 'order_outstanding' },
    { label: 'tax_title', value: 'tax_title' },
    { label: 'tax_rate', value: 'tax_rate' },
    { label: 'payment_gateway', value: 'payment_gateway' },
    { label: 'payment_terms_name', value: 'payment_terms_name' },
    { label: 'item_title', value: 'item_title' },
    { label: 'item_quantity', value: 'item_quantity' },
    { label: 'item_price', value: 'item_price' },
    { label: 'item_variant', value: 'item_variant' },
    { label: 'item_sku', value: 'item_sku' },
    { label: 'item_vendor', value: 'item_vendor' },
    { label: 'first_name', value: 'first_name' },
    { label: 'last_name', value: 'last_name' },
    { label: 'email', value: 'email' },
    { label: 'phone', value: 'phone' },
    { label: 'shipping_name', value: 'shipping_name' },
    { label: 'shipping_address1', value: 'shipping_address1' },
    { label: 'shipping_city', value: 'shipping_city' },
    { label: 'shipping_province', value: 'shipping_province' },
    { label: 'shipping_country', value: 'shipping_country' },
    { label: 'shipping_zip', value: 'shipping_zip' },
    { label: 'billing_name', value: 'billing_name' },
    { label: 'billing_address1', value: 'billing_address1' },
    { label: 'billing_city', value: 'billing_city' },
    { label: 'billing_province', value: 'billing_province' },
    { label: 'billing_country', value: 'billing_country' },
    { label: 'billing_zip', value: 'billing_zip' },
    { label: 'support_email', value: 'support_email' },
    { label: 'support_phone', value: 'support_phone' },
  ],
  14: [
    { label: 'order_id', value: 'order_id' },
    { label: 'order_name', value: 'order_name' },
    { label: 'order_number', value: 'order_number' },
    { label: 'confirmation_number', value: 'confirmation_number' },
    { label: 'order_date', value: 'order_date' },
    { label: 'order_updated_at', value: 'order_updated_at' },
    { label: 'order_total_price', value: 'order_total_price' },
    { label: 'current_total_price', value: 'current_total_price' },
    { label: 'order_currency', value: 'order_currency' },
    { label: 'payment_status', value: 'payment_status' },
    { label: 'fulfillment_status', value: 'fulfillment_status' },
    { label: 'confirmation_status', value: 'confirmation_status' },
    { label: 'order_status_url', value: 'order_status_url' },
    { label: 'total_outstanding', value: 'total_outstanding' },
    { label: 'customer_id', value: 'customer_id' },
    { label: 'first_name', value: 'first_name' },
    { label: 'last_name', value: 'last_name' },
    { label: 'email', value: 'email' },
    { label: 'phone', value: 'phone' },
    { label: 'default_address', value: 'default_address' },
    { label: 'billing_address', value: 'billing_address' },
    { label: 'shipping_address', value: 'shipping_address' },
    { label: 'shipping_method', value: 'shipping_method' },
    { label: 'shipping_price', value: 'shipping_price' },
    { label: 'tracking_number', value: 'tracking_number' },
    { label: 'tracking_url', value: 'tracking_url' },
    { label: 'item_id', value: 'item_id' },
    { label: 'item_title', value: 'item_title' },
    { label: 'item_quantity', value: 'item_quantity' },
    { label: 'item_price', value: 'item_price' },
    { label: 'item_variant_title', value: 'item_variant_title' },
    { label: 'item_product_id', value: 'item_product_id' },
    { label: 'item_vendor', value: 'item_vendor' },
    { label: 'subtotal', value: 'subtotal' },
    { label: 'current_subtotal_price', value: 'current_subtotal_price' },
    { label: 'total_discounts', value: 'total_discounts' },
    { label: 'current_total_discounts', value: 'current_total_discounts' },
    { label: 'total_tax', value: 'total_tax' },
    { label: 'total_weight', value: 'total_weight' },
    { label: 'payment_gateway', value: 'payment_gateway' },
    { label: 'presentment_currency', value: 'presentment_currency' },
    { label: 'transaction_id', value: 'transaction_id' },
    { label: 'transaction_kind', value: 'transaction_kind' },
    { label: 'transaction_status', value: 'transaction_status' },
    { label: 'transaction_amount', value: 'transaction_amount' },
    { label: 'transaction_currency', value: 'transaction_currency' },
    { label: 'transaction_credit_card_bin', value: 'transaction_credit_card_bin' },
    { label: 'transaction_credit_card_company', value: 'transaction_credit_card_company' },
    { label: 'transaction_created_at', value: 'transaction_created_at' },
    { label: 'source_name', value: 'source_name' },
    { label: 'browser_ip', value: 'browser_ip' },
    { label: 'support_email', value: 'support_email' },
    { label: 'support_phone', value: 'support_phone' },
  ],
  11: [
    { label: 'customer_firstname', value: 'customer_firstname' },
    { label: 'customer_order_count', value: 'customer_order_count' },
    { label: 'last_order_id', value: 'last_order_id' },
    { label: 'last_order_date', value: 'last_order_date' },
    { label: 'last_order_total', value: 'last_order_total' },
    { label: 'last_order_currency', value: 'last_order_currency' },
    { label: 'financial_status', value: 'financial_status' },
    { label: 'product_name', value: 'product_name' },
    { label: 'product_handle', value: 'product_handle' },
    { label: 'product_image_url', value: 'product_image_url' },
    { label: 'product_qty', value: 'product_qty' },
    { label: 'product_full_url', value: 'product_full_url' },
    { label: 'collection_url', value: 'collection_url' },
  ],
};

function getAvailableVariables(triggerCategory) {
  const cat = Number(triggerCategory);
  if (cat === 1) return AVAILABLE_VARIABLES_BY_CATEGORY[1];
  if (cat === 2) return AVAILABLE_VARIABLES_BY_CATEGORY[2];
  if ((cat >= 4 && cat <= 8) || cat === 22 || cat === 19 || cat === 23 || cat === 25) return AVAILABLE_VARIABLES_BY_CATEGORY.orderStatus;
  if (cat === 9 || cat === 10) return AVAILABLE_VARIABLES_BY_CATEGORY.paymentStatus;
  if (cat === 12) return AVAILABLE_VARIABLES_BY_CATEGORY[12];
  if (cat === 14) return AVAILABLE_VARIABLES_BY_CATEGORY[14];
  if (cat === 11) return AVAILABLE_VARIABLES_BY_CATEGORY[11];
  return [];
}

async function fetchTemplateListByCategory(triggerCategory) {
  const cat = Number(triggerCategory);
  if (cat === 1) return getAllTemplateListForAbandonedCart();
  if (cat === 2) return getAllTemplateListForOrderConfirmation();
  if ((cat >= 4 && cat <= 8) || cat === 22 || cat === 19 || cat === 23 || cat === 25) return getAllTemplateListForOrderStatus(triggerCategory);
  if (cat === 9 || cat === 10 || cat === 12 || cat === 14) return getAllTemplateListForOrderStatus(triggerCategory);
  if (cat === 11) return getAllTemplateListForReEngage();
  return getAllTemplateListForAbandonedCart();
}

function convertMinutesToTimeUnit(delayInMinutes) {
  const mins = Number(delayInMinutes) || 0;
  if (mins > 0 && mins % 1440 === 0) return { time: String(mins / 1440), unit: 'days' };
  if (mins > 0 && mins % 60 === 0) return { time: String(mins / 60), unit: 'hours' };
  return { time: String(mins), unit: 'minutes' };
}

function parseSelectedCollections(raw) {
  try {
    const str = typeof raw === 'string' ? raw.replace(/^"+|"+$/g, '') : raw;
    const parsed = JSON.parse(str);
    if (Array.isArray(parsed)) return parsed;
    if (parsed === '[All]' || parsed === 'All') return [];
    return [];
  } catch {
    return [];
  }
}

// --- main component ---

function EditTriggerPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const triggerId = searchParams.get('trigger_id');
  const triggerCategoryParam = searchParams.get('TriggerCategory');
  const triggerCategory = Number(triggerCategoryParam) || 1;

  const config = CATEGORY_CONFIG[triggerCategory] || CATEGORY_CONFIG[1];
  const availableVariables = getAvailableVariables(triggerCategory);

  // auth / account
  const [autoReplyToken, setAutoReplyToken] = useState(null);
  const [connected, setConnected] = useState(false);
  const [purchased, setPurchased] = useState(false);

  // loading / error
  const [loadingTrigger, setLoadingTrigger] = useState(true);
  const [fetchError, setFetchError] = useState(null);
  const [updatingTrigger, setUpdatingTrigger] = useState(false);
  const [triggerError, setTriggerError] = useState(null);

  // Static value state (body variables only)
  const [staticValueEnabled, setStaticValueEnabled] = useState({});
  const [staticValues, setStaticValues] = useState({});

  // form fields
  const [triggerName, setTriggerName] = useState('');
  const [triggerType, setTriggerType] = useState(String(triggerCategory));
  const [delayTime, setDelayTime] = useState('0');
  const [delayUnit, setDelayUnit] = useState('minutes');
  const [variableSelections, setVariableSelections] = useState({});

  // collection filter (category 1 only)
  const [filterByCollection, setFilterByCollection] = useState(false);
  const [selectedCollections, setSelectedCollections] = useState([]);
  const [collectionInputValue, setCollectionInputValue] = useState('');
  const [apiCollections, setApiCollections] = useState([]);
  const [loadingCollections, setLoadingCollections] = useState(false);
  const [collectionsError, setCollectionsError] = useState(null);

  // template
  const [apiTemplates, setApiTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [templateError, setTemplateError] = useState(null);
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [templateInputValue, setTemplateInputValue] = useState('');
  const [messageTemplate, setMessageTemplate] = useState('');
  const [selectedTemplateData, setSelectedTemplateData] = useState(null);
  const [loadingTemplateDetails, setLoadingTemplateDetails] = useState(false);
  const [mediaMapping, setMediaMapping] = useState({});
  const [uploadingMedia, setUploadingMedia] = useState({});
  const [urlButtonVariables, setUrlButtonVariables] = useState({});
  // 0 = dynamic (send job pulls per-customer file from Shopify), 1 = static (pinned Wasabi URL)
  const [sendStaticHeaderFile, setSendStaticHeaderFile] = useState(0);

  // order confirmation sub-category (category 2 only)
  const [orderTriggerSubCategory, setOrderTriggerSubCategory] = useState('prepaid');

  // re-engage scheduling fields (category 11 only)
  const [broadcastingIntervalValue, setBroadcastingIntervalValue] = useState('every_month');
  const [scheduledOnTime, setScheduledOnTime] = useState('10:00');
  const [selectedDayForBroadcasting, setSelectedDayForBroadcasting] = useState('1');
  const [targetCustomerCase, setTargetCustomerCase] = useState('months');
  const [targetCustomerCaseParam, setTargetCustomerCaseParam] = useState(3);
  const [targetCustomerDate, setTargetCustomerDate] = useState('');

  // --- load auth ---
  useEffect(() => {
    async function loadAuth() {
      try {
        await userDataReady;
        const autoToken = await getAutoReplyToken();
        setAutoReplyToken(autoToken);
        const accDetails = await getAccountDetails();
        setConnected(accDetails?.isAccountConnected || false);
        setPurchased(accDetails?.isplanpurchased || false);
      } catch (err) {
        console.error('Error loading auth:', err);
      }
    }
    loadAuth();
  }, []);

  // --- fetch template list ---
  useEffect(() => {
    async function loadTemplates() {
      try {
        setLoadingTemplates(true);
        const response = await fetchTemplateListByCategory(triggerType || triggerCategory);
        if (response.status && response.data?.customtemplates) {
          const transformed = response.data.customtemplates.map(t => ({
            id: t.template_id ? t.template_id.toString() : 'unknown',
            name: t.template_name || 'Unknown Template',
            templateId: t.template_id,
            label: t.template_name || 'Unknown Template',
            value: t.template_id ? t.template_id.toString() : 'unknown',
          }));
          setApiTemplates(transformed);
        } else {
          setApiTemplates([]);
        }
      } catch (err) {
        setTemplateError(`Failed to load templates: ${err.message}`);
        setApiTemplates([]);
      } finally {
        setLoadingTemplates(false);
      }
    }
    loadTemplates();
  }, [triggerType]);

  // --- fetch collections (category 1) ---
  useEffect(() => {
    if (!config.hasCollections) return;
    async function loadCollections() {
      try {
        setLoadingCollections(true);
        const response = await fetchallCategoryList({ perPageData: 200 });
        if (response.status && response.data?.data) {
          const transformed = response.data.data
            .filter(c => c.status === 1)
            .map(c => ({ id: c.id, label: c.category_name, value: c.id.toString() }));
          setApiCollections(transformed);
        }
      } catch (err) {
        setCollectionsError(`Failed to load collections: ${err.message}`);
      } finally {
        setLoadingCollections(false);
      }
    }
    loadCollections();
  }, [config.hasCollections]);

  // --- fetch trigger data and pre-fill ---
  useEffect(() => {
    if (!triggerId) {
      setFetchError('No trigger ID provided.');
      setLoadingTrigger(false);
      return;
    }
    async function loadTrigger() {
      try {
        setLoadingTrigger(true);
        const response = await fetchTriggerById(triggerId, triggerCategory);
        if (!response.success || !response.data?.trigger) {
          throw new Error('Invalid response from server');
        }
        const trigger = response.data.trigger;
        const templateFromResponse = response.data.TemplateJsonStructure?.data?.[0] || null;
        const reEngageSetting = response.data.re_engagement_setting || null;

        // Basic fields
        setTriggerName(trigger.triggerName || '');
        setTriggerType(String(trigger.TriggerCategory || triggerCategory));
        if (Number(trigger.TriggerCategory || triggerCategory) === 2) {
          setOrderTriggerSubCategory(trigger.OrderTriggerSubCategory || 'prepaid');
        }

        // Delay
        const { time, unit } = convertMinutesToTimeUnit(trigger.delayInMinutes);
        setDelayTime(time);
        setDelayUnit(unit);

        // Collections (category 1)
        if (config.hasCollections) {
          const rawCollections = response.data.selectedCollections || trigger.selectedCollections || '[All]';
          if (rawCollections && rawCollections !== '[All]') {
            const parsed = parseSelectedCollections(rawCollections);
            if (parsed.length > 0) {
              setFilterByCollection(true);
              setSelectedCollections(parsed);
            }
          }
        }

        // Re-engage settings (category 11)
        if (config.isReEngage && reEngageSetting) {
          setBroadcastingIntervalValue(reEngageSetting.broadcasting_interval || 'every_month');
          setScheduledOnTime(reEngageSetting.schedule_time || '10:00');
          setSelectedDayForBroadcasting(String(reEngageSetting.broadcasting_day || '1'));
          if (reEngageSetting.case) {
            setTargetCustomerCase(reEngageSetting.case);
            setTargetCustomerCaseParam(reEngageSetting.case_param || 3);
            if (reEngageSetting.case === 'date') {
              setTargetCustomerDate(reEngageSetting.case_param || '');
            }
          }
        }

        // Pre-fill Static/Dynamic header flag from the saved template structure
        const savedFlag = Number(trigger.triggertemplatestructure?.sendStaticHeaderFile ?? 0);
        setSendStaticHeaderFile(savedFlag === 1 ? 1 : 0);

        // Extract saved media URLs from JsonStructure (GetGabs CDN URLs — don't expire)
        const savedMediaMapping = {};
        const jsonStructureRaw = trigger.triggertemplatestructure?.JsonStructure;
        if (jsonStructureRaw) {
          try {
            const jsonStructure = JSON.parse(jsonStructureRaw);
            const savedComponents = jsonStructure.template?.components || [];
            savedComponents.forEach((comp) => {
              if (comp.type === 'HEADER' && Array.isArray(comp.parameters) && comp.parameters.length > 0) {
                const param = comp.parameters[0];
                const mediaUrl =
                  param?.image?.link ||
                  param?.video?.link ||
                  param?.document?.link ||
                  null;
                if (mediaUrl) {
                  // WhatsAppPreview always looks up 'header_0'
                  savedMediaMapping['header_0'] = {
                    link: mediaUrl,
                    fileUrl: mediaUrl,
                    url: mediaUrl,
                    uploaded: true,
                  };
                }
              }
            });
          } catch (e) {
            console.warn('Could not parse JsonStructure for media URLs:', e);
          }
        }

        // Pre-fill template
        if (templateFromResponse) {
          setSelectedTemplateData(templateFromResponse);
          setSelectedTemplateId(trigger.assignedTemplateId ? trigger.assignedTemplateId.toString() : '');
          setSelectedTemplate(trigger.assignedTemplateId ? trigger.assignedTemplateId.toString() : '');
          setTemplateInputValue(trigger.template_name || '');

          // Build message text from components
          let content = '';
          if (templateFromResponse.components) {
            templateFromResponse.components.forEach(c => {
              if (c.type === 'HEADER' && c.text) content += c.text + '\n\n';
              else if (c.type === 'BODY' && c.text) content += c.text + '\n\n';
              else if (c.type === 'FOOTER' && c.text) content += c.text;
            });
          }
          setMessageTemplate(content.trim());
        } else if (trigger.template_name) {
          // Fallback: fetch fresh template by name
          try {
            setLoadingTemplateDetails(true);
            const tmplResponse = await getSelectedTemplatebyName(trigger.template_name);
            if (tmplResponse.data?.length > 0) {
              const tmplData = tmplResponse.data[0];
              setSelectedTemplateData(tmplData);
              setSelectedTemplateId(trigger.assignedTemplateId ? trigger.assignedTemplateId.toString() : '');
              setSelectedTemplate(trigger.assignedTemplateId ? trigger.assignedTemplateId.toString() : '');
              setTemplateInputValue(trigger.template_name);
              let content = '';
              tmplData.components?.forEach(c => {
                if (c.type === 'HEADER' && c.text) content += c.text + '\n\n';
                else if (c.type === 'BODY' && c.text) content += c.text + '\n\n';
                else if (c.type === 'FOOTER' && c.text) content += c.text;
              });
              setMessageTemplate(content.trim());
            }
          } catch {
            // ignore fallback failures
          } finally {
            setLoadingTemplateDetails(false);
          }
        }

        // Seed mediaMapping with saved GetGabs CDN URLs (must run after template set)
        if (Object.keys(savedMediaMapping).length > 0) {
          setMediaMapping(savedMediaMapping);
        }
      } catch (err) {
        console.error('Error loading trigger:', err);
        setFetchError(err.message || 'Failed to load trigger data');
      } finally {
        setLoadingTrigger(false);
      }
    }
    loadTrigger();
  }, [triggerId, triggerCategory]);

  // --- template change handler ---
  const allTemplateOptions = useMemo(() => apiTemplates, [apiTemplates]);

  const filteredTemplateOptions = useMemo(() => {
    if (!templateInputValue.trim()) return allTemplateOptions;
    const lower = templateInputValue.toLowerCase();
    return allTemplateOptions.filter(t =>
      t.label?.toLowerCase().includes(lower) || t.name?.toLowerCase().includes(lower)
    );
  }, [allTemplateOptions, templateInputValue]);

  const handleTemplateChange = useCallback(async (value) => {
    setSelectedTemplateId(value);
    const tmpl = allTemplateOptions.find(t => t.id === value || t.value === value);
    if (!tmpl) {
      setTemplateInputValue('');
      setSelectedTemplate('');
      setMessageTemplate('');
      setSelectedTemplateData(null);
      setVariableSelections({});
      setMediaMapping({});
      setUrlButtonVariables({});
      setStaticValueEnabled({});
      setStaticValues({});
      return;
    }
    setTemplateInputValue(tmpl.label);
    setSelectedTemplate(tmpl.value);

    try {
      setLoadingTemplateDetails(true);
      setTemplateError(null);
      const response = await getSelectedTemplatebyName(tmpl.name);
      if (response.data?.length > 0) {
        const tmplData = response.data[0];
        setSelectedTemplateData(tmplData);
        let content = '';
        tmplData.components?.forEach(c => {
          if (c.type === 'HEADER' && c.text) content += c.text + '\n\n';
          else if (c.type === 'BODY' && c.text) content += c.text + '\n\n';
          else if (c.type === 'FOOTER' && c.text) content += c.text;
        });
        setMessageTemplate(content.trim());
      } else {
        setTemplateError('Template not found or invalid');
        setSelectedTemplateData(null);
      }
    } catch (err) {
      setTemplateError(`Failed to load template: ${err.message}`);
      setSelectedTemplateData(null);
    } finally {
      setLoadingTemplateDetails(false);
    }
    setVariableSelections({});
    setMediaMapping({});
    setUrlButtonVariables({});
    setStaticValueEnabled({});
    setStaticValues({});
  }, [allTemplateOptions]);

  // --- variable / media / url-button handlers ---
  const handleVariableSelectionChange = useCallback((variable, value) => {
    setVariableSelections(prev => ({ ...prev, [variable]: value }));
  }, []);

  const handleStaticValueToggle = useCallback((variable) => {
    setStaticValueEnabled(prev => {
      const newEnabled = { ...prev, [variable]: !prev[variable] };
      if (!newEnabled[variable]) {
        setStaticValues(prevStatic => {
          const newStatic = { ...prevStatic };
          delete newStatic[variable];
          return newStatic;
        });
      }
      return newEnabled;
    });
  }, []);

  const handleStaticValueChange = useCallback((variable, value) => {
    setStaticValues(prev => ({ ...prev, [variable]: value }));
  }, []);

  const handleUrlButtonVariableChange = useCallback((buttonIndex, value) => {
    setUrlButtonVariables(prev => ({ ...prev, [buttonIndex]: value }));
  }, []);

  const handleMediaMappingChange = useCallback(async (mediaKey, file) => {
    if (!file) {
      setMediaMapping(prev => ({
        ...prev,
        [mediaKey]: { ...prev[mediaKey], file: null, fileUrl: null, fileName: null, uploaded: false, uploadError: null },
      }));
      return;
    }
    setUploadingMedia(prev => ({ ...prev, [mediaKey]: true }));
    try {
      const reader = new FileReader();
      reader.onload = async () => {
        try {
          const base64String = reader.result.split(',')[1];
          let fileType = 'image';
          if (file.type.startsWith('video/')) fileType = 'video';
          else if (file.type.startsWith('audio/')) fileType = 'audio';
          else if (file.type.includes('pdf') || file.type.includes('document') || file.type.includes('text')) fileType = 'document';

          const uploadResponse = await saveTemporaryFile({
            fileName: file.name,
            fileSrc: `data:${file.type};base64,${base64String}`,
            fileType,
          });

          if (uploadResponse.status && uploadResponse.filename) {
            const fileUrl = `https://app.getgabs.com/partners/fileManage/Gallery/Campaign/Upload/customers/mediafile/newfiles/uploads/${uploadResponse.filename}`;
            setMediaMapping(prev => ({
              ...prev,
              [mediaKey]: { ...prev[mediaKey], file, fileUrl, fileName: uploadResponse.filename, uploaded: true, uploadError: null },
            }));
          } else {
            throw new Error(uploadResponse.message || 'Failed to upload file');
          }
        } catch (err) {
          setMediaMapping(prev => ({ ...prev, [mediaKey]: { ...prev[mediaKey], uploadError: err.message } }));
          setTemplateError(`Failed to upload file: ${err.message}`);
        } finally {
          setUploadingMedia(prev => ({ ...prev, [mediaKey]: false }));
        }
      };
      reader.onerror = () => {
        setTemplateError('Failed to read file');
        setUploadingMedia(prev => ({ ...prev, [mediaKey]: false }));
      };
      reader.readAsDataURL(file);
    } catch (err) {
      setTemplateError(`Failed to upload file: ${err.message}`);
      setUploadingMedia(prev => ({ ...prev, [mediaKey]: false }));
    }
  }, []);

  // --- collection handlers ---
  const handleCollectionSelect = useCallback((val) => {
    if (val && !selectedCollections.includes(val) && selectedCollections.length < 5) {
      setSelectedCollections(prev => [...prev, val]);
    }
    setCollectionInputValue('');
  }, [selectedCollections]);

  const handleCollectionRemove = useCallback((val) => {
    setSelectedCollections(prev => prev.filter(c => c !== val));
  }, []);

  // --- computed template data ---
  const extractVariables = useMemo(() => {
    return extractVariablesFromWhatsAppMessage(messageTemplate);
  }, [messageTemplate]);

  // Track which variables belong to BODY components only
  const bodyVariableSet = useMemo(() => {
    const vars = new Set();
    if (!selectedTemplateData?.components) return vars;
    selectedTemplateData.components.forEach(component => {
      if (component.type === 'BODY' && component.text) {
        extractVariablesFromWhatsAppMessage(component.text).forEach(v => vars.add(v));
      }
    });
    return vars;
  }, [selectedTemplateData]);

  useEffect(() => {
    if (extractVariables.length === 0) return;
    const autoMapped = {};
    extractVariables.forEach(variable => {
      const match = availableVariables.find(av => av.value.toLowerCase() === variable.toLowerCase());
      if (match && !variableSelections[variable]) {
        autoMapped[variable] = match.value;
      }
    });
    if (Object.keys(autoMapped).length > 0) {
      setVariableSelections(prev => ({ ...prev, ...autoMapped }));
    }
  }, [extractVariables]);

  const templateMedia = useMemo(() => {
    if (!selectedTemplateData?.components) return {};
    const media = {};
    selectedTemplateData.components.forEach((component, index) => {
      if (component.type === 'HEADER' && ['IMAGE', 'VIDEO', 'DOCUMENT'].includes(component.format)) {
        media[`header_${index}`] = {
          type: component.format.toLowerCase(),
          url: component.example?.header_handle?.[0] || null,
          required: true,
        };
      }
    });
    return media;
  }, [selectedTemplateData]);

  // Video, document, and location headers cannot be pulled dynamically from
  // Shopify at send time — the backend forces sendStaticHeaderFile = 1 for
  // these types (see HandlesTemplateStaticHeader::resolveStaticHeaderFlag).
  const headerRequiresStatic = useMemo(
    () => Object.values(templateMedia).some(
      m => m.type === 'video' || m.type === 'document' || m.type === 'location'
    ),
    [templateMedia],
  );
  const effectiveStaticHeaderFile = headerRequiresStatic ? 1 : sendStaticHeaderFile;

  const templateUrlButtons = useMemo(() => {
    if (!selectedTemplateData?.components) return [];
    const buttons = [];
    selectedTemplateData.components.forEach(component => {
      if (component.type === 'BUTTONS' && component.buttons) {
        component.buttons.forEach((btn, i) => {
          if (btn.type === 'URL' && btn.url && /\{\{\d+\}\}/.test(btn.url)) {
            buttons.push({ index: i, text: btn.text, url: btn.url, example: btn.example?.[0] || '' });
          }
        });
      }
    });
    return buttons;
  }, [selectedTemplateData]);

  useEffect(() => {
    if (templateUrlButtons.length === 0) return;
    const initial = {};
    templateUrlButtons.forEach(btn => {
      if (!urlButtonVariables[btn.index]) initial[btn.index] = btn.example;
    });
    if (Object.keys(initial).length > 0) {
      setUrlButtonVariables(prev => ({ ...prev, ...initial }));
    }
  }, [templateUrlButtons]);

  const filteredCollectionOptions = useMemo(() => {
    if (selectedCollections.length >= 5) return [];
    return apiCollections.filter(opt =>
      !selectedCollections.includes(opt.value) &&
      (!collectionInputValue || opt.label.toLowerCase().includes(collectionInputValue.toLowerCase()))
    );
  }, [apiCollections, collectionInputValue, selectedCollections]);

  const isFormValid = useMemo(() => {
    if (!triggerName.trim()) return false;
    if (!selectedTemplateData) return false;
    if (updatingTrigger) return false;
    return true;
  }, [triggerName, selectedTemplateData, updatingTrigger]);

  // --- save handler ---
  const handleSave = useCallback(async () => {
    try {
      setUpdatingTrigger(true);
      setTriggerError(null);

      if (!triggerName.trim()) throw new Error('Please enter a trigger name');
      if (!selectedTemplateData) throw new Error('Please select a template');

      // Build template components (same logic as create pages)
      const components = [];
      selectedTemplateData.components?.forEach((component, index) => {
        if (component.type === 'HEADER') {
          if (['IMAGE', 'VIDEO', 'DOCUMENT'].includes(component.format)) {
            const mediaFile = mediaMapping[`header_${index}`];
            components.push({
              type: 'HEADER',
              parameters: [{
                type: component.format,
                [component.format.toLowerCase()]: {
                  link: mediaFile?.fileUrl || component.example?.header_handle?.[0] || ''
                }
              }]
            });
          } else if (component.text) {
            const vars = extractVariablesFromWhatsAppMessage(component.text);
            if (vars.length > 0) {
              components.push({
                type: 'HEADER',
                parameters: vars.map(v => ({ type: 'text', parameter_name: v, text: `{${variableSelections[v]}}` }))
              });
            }
          }
        } else if (component.type === 'BODY' && component.text) {
          const vars = extractVariablesFromWhatsAppMessage(component.text);
          if (vars.length > 0) {
            components.push({
              type: 'BODY',
              parameters: vars.map(v => ({
                type: 'text',
                parameter_name: v,
                text: staticValueEnabled[v] && staticValues[v]
                  ? staticValues[v]
                  : `{${variableSelections[v]}}`
              }))
            });
          }
        } else if (component.type === 'BUTTONS' && component.buttons) {
          const btnParams = [];
          const urlVariableRegex = /\{\{\s*\d+\s*\}\}/;
          // Abandoned cart triggers (category 1) must ALWAYS use {checkoutId}/{userId}
          // so the backend InjectsCheckoutPath trait can swap in the real redirect URL
          // — same rule for Shopify/CashFree/Shopflo/GoKwik/Razorpay/Shiprocket carts.
          const isAbandonedCart = Number(triggerType) === 1;
          component.buttons.forEach((btn, i) => {
            if (btn.type !== 'URL' || !btn.url) return;
            const hasVariable = urlVariableRegex.test(btn.url);
            const hasExample = Array.isArray(btn.example) && btn.example.length > 0;
            if (!hasVariable && !hasExample) return;
            const text = isAbandonedCart
              ? '{checkoutId}/{userId}'
              : `{${urlButtonVariables[i] || btn.example?.[0] || '1'}}`;
            btnParams.push({
              type: 'button',
              sub_type: 'URL',
              index: i,
              parameters: [{ type: 'text', text }]
            });
          });
          if (btnParams.length > 0) components.push(...btnParams);
        }
      });

      // Derive formId per trigger category (mirrors create pages)
      const formIdMap = { 1: 'abandonedCartTemplateForm' };
      const formId = formIdMap[Number(triggerType)] || 'orderConfirmationTemplateForm';

      // Derive triggerType string (mirrors create pages)
      const triggerTypeStr = Number(triggerType) === 1 ? 'abandoned_cart'
        : Number(triggerType) === 2 ? 'order_confirmation'
          : String(triggerType);

      const payload = {
        // Edit-specific required fields
        trigger_id: Number(triggerId),
        TriggerName: triggerName.trim(),
        TriggerCategory: Number(triggerType),
        TemplateName: selectedTemplateData.name || templateInputValue,

        // Create-style fields
        _token: autoReplyToken,
        template_type: 'template',
        formId,
        templateJson: {
          to: 'receiver_number',
          type: 'template',
          template: {
            name: selectedTemplateData.name || '',
            language: { code: selectedTemplateData.language || 'en_US' },
            components,
          },
          recipient_type: 'individual',
          messaging_product: 'whatsapp',
        },
        currentChoosedTemplateJson: {
          choosedTemplate: {
            name: selectedTemplateData.name || '',
            parameter_format: selectedTemplateData.parameter_format || 'POSITIONAL',
            components: selectedTemplateData.components || [],
            language: selectedTemplateData.language || 'en_US',
            status: selectedTemplateData.status || 'APPROVED',
            category: selectedTemplateData.category || 'MARKETING',
            id: selectedTemplateData.id || selectedTemplateData.template_id || '',
          },
        },
        triggerName: triggerName.trim(),
        triggerType: triggerTypeStr,
        delayTime,
        delayUnit,
        selectedCollections: config.hasCollections && filterByCollection
          ? JSON.stringify(selectedCollections)
          : '[All]',
        sendStaticHeaderFile: effectiveStaticHeaderFile,
        ...(Number(triggerType) === 2 && { OrderTriggerSubCategory: orderTriggerSubCategory }),
      };

      // Re-engage extra fields (TriggerCategory = 11)
      if (config.isReEngage) {
        payload.ReEngage = true;
        payload.case = targetCustomerCase;
        payload.case_param = targetCustomerCaseParam;
        payload.schedule_time = scheduledOnTime;
        payload.broadcasting_day = selectedDayForBroadcasting;
        payload.broadcasting_interval = broadcastingIntervalValue;
      }

      await updateTrigger(payload);
      navigate(config.backPath);
    } catch (err) {
      setTriggerError(err.message || 'Failed to update trigger');
    } finally {
      setUpdatingTrigger(false);
    }
  }, [
    triggerId, triggerName, triggerType, selectedTemplateData, templateInputValue,
    autoReplyToken, delayTime, delayUnit, mediaMapping, variableSelections, staticValueEnabled, staticValues, urlButtonVariables,
    filterByCollection, selectedCollections, config, orderTriggerSubCategory,
    targetCustomerCase, targetCustomerCaseParam, scheduledOnTime,
    selectedDayForBroadcasting, broadcastingIntervalValue, navigate,
    effectiveStaticHeaderFile,
  ]);

  const handleCancel = useCallback(() => navigate(config.backPath), [navigate, config.backPath]);

  // --- trigger type options for order-status / payment-status ---
  const triggerTypeSelectOptions = useMemo(() => {
    if ((triggerCategory >= 4 && triggerCategory <= 8) || triggerCategory === 22 || triggerCategory === 19 || triggerCategory === 23 || triggerCategory === 25) return ORDER_STATUS_TYPE_OPTIONS;
    if (triggerCategory === 9 || triggerCategory === 10 || triggerCategory === 12) return PAYMENT_STATUS_TYPE_OPTIONS;
    return [];
  }, [triggerCategory]);

  // --- loading state ---
  if (loadingTrigger) {
    return (
      <Page title={`Edit ${config.label} Trigger`} fullWidth>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '4rem' }}>
          <BlockStack gap="400" inlineAlign="center">
            <Spinner size="large" />
            <Text variant="bodyMd" tone="subdued">Loading trigger data...</Text>
          </BlockStack>
        </div>
      </Page>
    );
  }

  if (fetchError) {
    return (
      <Page
        title={`Edit ${config.label} Trigger`}
        backAction={{ content: 'Back', onAction: handleCancel }}
        fullWidth
      >
        <Banner tone="critical" title="Failed to load trigger">
          <Text as="p">{fetchError}</Text>
          <Button onClick={handleCancel}>Go Back</Button>
        </Banner>
      </Page>
    );
  }

  return (
    <Page
      title={`Edit ${config.label} Trigger`}
      subtitle={`Update your automated ${config.label.toLowerCase()} message trigger`}
      backAction={{ content: `${config.label} Triggers`, onAction: handleCancel }}
      primaryAction={{
        content: 'Update Trigger',
        onAction: handleSave,
        disabled: !isFormValid,
        loading: updatingTrigger,
      }}
      secondaryActions={[{ content: 'Cancel', onAction: handleCancel }]}
      fullWidth
    >
      <Grid>
        {/* ---- LEFT COLUMN ---- */}
        <Grid.Cell columnSpan={{ xs: 6, sm: 6, md: 8, lg: 8, xl: 8 }}>
          <BlockStack gap="500">
            {templateError && (
              <Banner tone="critical" onDismiss={() => setTemplateError(null)}>
                <Text as="p">{templateError}</Text>
              </Banner>
            )}
            {triggerError && (
              <Banner tone="critical" onDismiss={() => setTriggerError(null)}>
                <Text as="p">{triggerError}</Text>
              </Banner>
            )}

            {/* Basic Information */}
            <Card>
              <BlockStack gap="400">
                <Text variant="headingMd" as="h2">Basic Information</Text>
                <FormLayout>
                  <TextField
                    label="Trigger Name"
                    value={triggerName}
                    onChange={setTriggerName}
                    placeholder="e.g., Abandoned Cart Recovery - 30 minutes"
                    helpText="Give your trigger a descriptive name"
                    requiredIndicator
                  />
                  {config.hasTriggerTypeSelect ? (
                    <Select
                      label="Trigger Type"
                      options={triggerTypeSelectOptions}
                      value={triggerType}
                      onChange={(val) => setTriggerType(val)}
                      helpText="Select the specific event this trigger responds to"
                    />
                  ) : (
                    <TextField
                      label="Trigger Type"
                      value={config.label}
                      disabled
                      helpText="This trigger type cannot be changed"
                    />
                  )}

                  {triggerCategory === 2 && (
                    <Select
                      label="Trigger Sub-Category"
                      options={[
                        { label: 'Prepaid', value: 'prepaid' },
                        { label: 'COD', value: 'postpaid' },
                        { label: 'COD to Prepaid', value: 'cod_to_prepaid' },
                      ]}
                      value={orderTriggerSubCategory}
                      onChange={setOrderTriggerSubCategory}
                      helpText="Select whether this trigger applies to prepaid or COD orders"
                    />
                  )}
                </FormLayout>
              </BlockStack>
            </Card>

            {/* Template Selection */}
            <Card>
              <BlockStack gap="400">
                <Text variant="headingMd" as="h2">Template Selection</Text>
                <FormLayout>
                  {loadingTemplates ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '12px' }}>
                      <Spinner size="small" />
                      <Text variant="bodySm" tone="subdued">Loading templates...</Text>
                    </div>
                  ) : allTemplateOptions.length > 0 ? (
                    <BlockStack gap="200">
                      <Autocomplete
                        label="Search and select template"
                        options={filteredTemplateOptions.map(t => ({ value: t.id || t.value, label: t.label }))}
                        selected={selectedTemplateId ? [selectedTemplateId] : []}
                        onSelect={(selected) => { if (selected[0]) handleTemplateChange(selected[0]); }}
                        textField={
                          <Autocomplete.TextField
                            onChange={setTemplateInputValue}
                            label="Search and select template"
                            value={templateInputValue}
                            placeholder="Type to search templates..."
                            autoComplete="off"
                          />
                        }
                        loading={loadingTemplates || loadingTemplateDetails}
                        emptyState={loadingTemplates ? 'Loading templates...' : 'No templates found'}
                        preferredPosition="below"
                        willLoadMoreResults={false}
                      />
                      <Text variant="bodySm" tone="subdued">
                        Found {allTemplateOptions.length} templates
                      </Text>
                      {selectedTemplateData && (
                        <Banner tone="info">
                          <Text variant="bodyMd" as="p">
                            Template selected: <strong>{allTemplateOptions.find(t => t.id === selectedTemplateId || t.value === selectedTemplateId)?.label || templateInputValue}</strong>
                            {loadingTemplateDetails && <span> (Loading details...)</span>}
                          </Text>
                        </Banner>
                      )}
                    </BlockStack>
                  ) : (
                    <div style={{ padding: '12px', textAlign: 'center' }}>
                      <Text variant="bodySm" tone="subdued">No templates available. </Text>
                    </div>
                  )}
                  <Text variant="bodySm" tone="subdued">Search and select from available templates</Text>
                </FormLayout>
              </BlockStack>
            </Card>

            {/* Variable Mapping */}
            {extractVariables.length > 0 && (
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">Variable Mapping</Text>
                  <Text variant="bodySm" as="p" tone="subdued">Map the template variables to actual data fields:</Text>
                  <FormLayout>
                    {extractVariables.map((variable) => {
                      const isBodyVar = bodyVariableSet.has(variable);
                      const isStatic = isBodyVar && staticValueEnabled[variable];
                      return (
                        <BlockStack key={variable} gap="200">
                          <InlineStack align="space-between" blockAlign="center">
                            <Text variant="bodyMd" as="p" fontWeight="medium">
                              {`{{${variable}}}`}
                            </Text>
                            {isBodyVar && (
                              <Button
                                variant="plain"
                                size="slim"
                                onClick={() => handleStaticValueToggle(variable)}
                              >
                                {isStatic ? 'Use Field Mapping' : 'Add Static Value'}
                              </Button>
                            )}
                          </InlineStack>
                          {isStatic ? (
                            <TextField
                              label={`Static value for {{${variable}}}`}
                              value={staticValues[variable] || ''}
                              onChange={(value) => handleStaticValueChange(variable, value)}
                              placeholder={`Enter a fixed value for {{${variable}}}`}
                              helpText="This value will be sent as-is for all customers"
                            />
                          ) : (
                            <Select
                              label="Map to"
                              options={[{ label: 'Select mapping...', value: '' }, ...availableVariables]}
                              value={variableSelections[variable] || ''}
                              onChange={(value) => handleVariableSelectionChange(variable, value)}
                            />
                          )}
                        </BlockStack>
                      );
                    })}
                  </FormLayout>
                </BlockStack>
              </Card>
            )}

            {/* Media Files */}
            {Object.keys(templateMedia).length > 0 && (
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">Media Files</Text>
                  <Text variant="bodySm" as="p" tone="subdued">Upload media files required by this template:</Text>
                  <ChoiceList
                    title="Header source"
                    choices={[
                      {
                        label: 'Dynamic — pull from Shopify at send time',
                        value: '0',
                        helpText: 'The customer\'s cart/order media (e.g. product image) is fetched and used per send. Applies only to image headers.',
                      },
                      {
                        label: 'Static — use the uploaded file for every send',
                        value: '1',
                        helpText: 'The uploaded file is rehosted on app.getgabs.com and sent to every customer as-is.',
                      },
                    ]}
                    selected={[String(effectiveStaticHeaderFile)]}
                    onChange={(vals) => setSendStaticHeaderFile(vals[0] === '1' ? 1 : 0)}
                    disabled={headerRequiresStatic}
                  />
                  {headerRequiresStatic && (
                    <Text variant="bodySm" as="p" tone="subdued">
                      Video and document headers must be static — dynamic per-customer files aren't supported for these types.
                    </Text>
                  )}
                  <BlockStack gap="400">
                    {Object.entries(templateMedia).map(([mediaKey, mediaData]) => {
                      const uploadedFile = mediaMapping[mediaKey]?.file;
                      // Resolve display URL: new upload > saved GetGabs URL > example header_handle URL
                      const displayUrl =
                        mediaMapping[mediaKey]?.fileUrl ||
                        mediaMapping[mediaKey]?.link ||
                        mediaMapping[mediaKey]?.url ||
                        mediaData.url ||
                        null;
                      const isUploading = uploadingMedia[mediaKey];
                      const uploadError = mediaMapping[mediaKey]?.uploadError;
                      const isUploaded = mediaMapping[mediaKey]?.uploaded;
                      const hasMedia = !!(displayUrl);
                      return (
                        <BlockStack key={mediaKey} gap="200">
                          <InlineStack gap="200" align="space-between" blockAlign="center">
                            <InlineStack gap="200" blockAlign="center">
                              <Thumbnail
                                source={displayUrl || FolderIcon}
                                alt={uploadedFile?.name || `Header ${mediaData.type}`}
                                size="small"
                              />
                              <BlockStack gap="050">
                                <InlineStack gap="200" blockAlign="center">
                                  <Text variant="bodyMd" as="p">
                                    {uploadedFile ? uploadedFile.name : `Header ${mediaData.type}`}
                                  </Text>
                                  {isUploading && <Badge tone="info">Uploading...</Badge>}
                                  {isUploaded && !isUploading && <Badge tone="success">Saved</Badge>}
                                </InlineStack>
                                <Text variant="bodySm" as="p" tone="subdued">
                                  {uploadedFile
                                    ? `${(uploadedFile.size / 1024 / 1024).toFixed(2)} MB`
                                    : hasMedia ? `Current ${mediaData.type}` : `No ${mediaData.type} uploaded`}
                                </Text>
                                {uploadError && <Text variant="bodySm" as="p" tone="critical">Error: {uploadError}</Text>}
                              </BlockStack>
                            </InlineStack>
                            {hasMedia ? (
                              <InlineStack gap="100">
                                <Button
                                  variant="plain"
                                  size="slim"
                                  onClick={() => document.getElementById(`upload-${mediaKey}`).click()}
                                  disabled={isUploading}
                                  loading={isUploading}
                                >
                                  Replace
                                </Button>
                              </InlineStack>
                            ) : (
                              <Button variant="plain" size="slim" onClick={() => document.getElementById(`upload-${mediaKey}`).click()} disabled={isUploading} loading={isUploading}>
                                Upload {mediaData.type}
                              </Button>
                            )}
                          </InlineStack>
                          <input
                            id={`upload-${mediaKey}`}
                            type="file"
                            accept={mediaData.type === 'image' ? 'image/*' : mediaData.type === 'video' ? 'video/*' : 'application/pdf,.doc,.docx,.txt'}
                            style={{ display: 'none' }}
                            onChange={e => { if (e.target.files?.length > 0) handleMediaMappingChange(mediaKey, e.target.files[0]); }}
                          />
                        </BlockStack>
                      );
                    })}
                  </BlockStack>
                </BlockStack>
              </Card>
            )}

            {/* URL Button Variables */}
            {templateUrlButtons.length > 0 && (
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">URL Button Variables</Text>
                  <Text variant="bodySm" as="p" tone="subdued">Configure the default values for URL button variables:</Text>
                  <FormLayout>
                    {templateUrlButtons.map(btn => (
                      <FormLayout.Group key={`url_button_${btn.index}`}>
                        <TextField label={`Button: ${btn.text}`} value={btn.url} disabled helpText="URL template with variable placeholder" />
                        <TextField
                          label="Variable value"
                          value={urlButtonVariables[btn.index] || btn.example}
                          disabled
                          helpText="This value will replace the variable in the URL"
                        />
                      </FormLayout.Group>
                    ))}
                  </FormLayout>
                </BlockStack>
              </Card>
            )}

            {/* Timing Settings */}
            <Card>
              <BlockStack gap="400">
                <Text variant="headingMd" as="h2">Timing Settings</Text>
                <FormLayout>
                  <FormLayout.Group>
                    <TextField
                      label="Delay Time"
                      type="number"
                      value={delayTime}
                      onChange={setDelayTime}
                      min="0"
                      helpText="How long to wait before sending the message"
                    />
                    <Select
                      label="Delay Unit"
                      options={[
                        { label: 'Minutes', value: 'minutes' },
                        { label: 'Hours', value: 'hours' },
                        { label: 'Days', value: 'days' },
                      ]}
                      value={delayUnit}
                      onChange={setDelayUnit}
                    />
                  </FormLayout.Group>
                </FormLayout>
              </BlockStack>
            </Card>

            {/* Target Audience - Collection filter (category 1 only) */}
            {config.hasCollections && (
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">Target Audience</Text>
                  <BlockStack gap="300">
                    <Text as="p" tone="subdued">This trigger targets customers who abandon their shopping carts.</Text>
                    <Checkbox label="Abandoned Cart Customers" checked={true} disabled helpText="Automatically selected for abandoned cart triggers" />
                    <Checkbox
                      label="Filter target customers by product category/collection?"
                      checked={filterByCollection}
                      onChange={(val) => {
                        setFilterByCollection(val);
                        if (!val) { setSelectedCollections([]); setCollectionInputValue(''); }
                      }}
                    />
                    {filterByCollection && (
                      <FormLayout>
                        {collectionsError && (
                          <Banner title="Collections Error" tone="critical" onDismiss={() => setCollectionsError(null)}>
                            <p>{collectionsError}</p>
                          </Banner>
                        )}
                        {loadingCollections && (
                          <InlineStack gap="200" align="center">
                            <Spinner size="small" />
                            <Text variant="bodySm" as="p" tone="subdued">Loading collections...</Text>
                          </InlineStack>
                        )}
                        <BlockStack gap="200">
                          <InlineStack align="space-between">
                            <Text variant="bodyMd" as="h3">Select Collections (Maximum 5)</Text>
                            <Text variant="bodySm" as="p" tone={selectedCollections.length >= 5 ? 'critical' : 'subdued'}>
                              {selectedCollections.length}/5 selected
                            </Text>
                          </InlineStack>
                          {selectedCollections.length > 0 && (
                            <InlineStack gap="100" wrap>
                              {selectedCollections.map(val => {
                                const opt = apiCollections.find(o => o.value === val);
                                return (
                                  <Tag key={val} onRemove={() => handleCollectionRemove(val)}>
                                    {opt ? opt.label : val}
                                  </Tag>
                                );
                              })}
                            </InlineStack>
                          )}
                          <Combobox
                            activator={
                              <Combobox.TextField
                                onChange={setCollectionInputValue}
                                label=""
                                labelHidden
                                value={collectionInputValue}
                                placeholder={selectedCollections.length >= 5 ? 'Maximum 5 collections selected' : 'Search and select collections...'}
                                autoComplete="off"
                                disabled={selectedCollections.length >= 5 || loadingCollections}
                              />
                            }
                          >
                            {filteredCollectionOptions.length > 0 ? (
                              <Listbox onSelect={handleCollectionSelect}>
                                {filteredCollectionOptions.map(opt => (
                                  <Listbox.Option key={opt.value} value={opt.value} selected={selectedCollections.includes(opt.value)}>
                                    {opt.label}
                                  </Listbox.Option>
                                ))}
                              </Listbox>
                            ) : (
                              <Listbox>
                                <Listbox.Option value="" disabled>
                                  {selectedCollections.length >= 5 ? 'Maximum selected' : 'No collections found'}
                                </Listbox.Option>
                              </Listbox>
                            )}
                          </Combobox>
                          <Text variant="bodySm" as="p" tone="subdued">
                            Only customers with products from selected collections in their cart will receive this trigger. Maximum 5.
                          </Text>
                        </BlockStack>
                      </FormLayout>
                    )}
                  </BlockStack>
                </BlockStack>
              </Card>
            )}

            {/* Re-engage Settings (category 11 only) */}
            {config.isReEngage && (
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">Target Audience & Schedule</Text>
                  <BlockStack gap="300">
                    <Select
                      label="Target Customer From Last Order Date"
                      options={[
                        { label: 'Last 1 Month', value: 'months_1' },
                        { label: 'Last 2 Month', value: 'months_2' },
                        { label: 'Last 3 Month', value: 'months_3' },
                        { label: 'Last 6 Month', value: 'months_6' },
                        { label: 'Never', value: 'never_never' },
                        { label: 'Select date before', value: 'date_custom' },
                      ]}
                      value={targetCustomerCase === 'date' ? 'date_custom' : `${targetCustomerCase}_${targetCustomerCaseParam}`}
                      onChange={(value) => {
                        if (value === 'date_custom') {
                          setTargetCustomerCase('date');
                          setTargetCustomerCaseParam(targetCustomerDate);
                        } else {
                          const [c, p] = value.split('_');
                          setTargetCustomerCase(c);
                          setTargetCustomerCaseParam(c === 'never' ? 'never' : parseInt(p));
                        }
                      }}
                    />
                    {targetCustomerCase === 'date' && (
                      <TextField
                        type="date"
                        label="Select Date Before"
                        value={targetCustomerDate}
                        onChange={(val) => { setTargetCustomerDate(val); setTargetCustomerCaseParam(val); }}
                        helpText="Customers who ordered before this date will be targeted"
                      />
                    )}
                    <FormLayout>
                      <FormLayout.Group>
                        <Select
                          label="Broadcasting Interval"
                          options={[
                            { label: 'Every Month', value: 'every_month' },
                            { label: 'Every 2 Month', value: 'every_2month' },
                            { label: 'Every 3 Month', value: 'every_3month' },
                            { label: 'Every 6 Month', value: 'every_6month' },
                          ]}
                          value={broadcastingIntervalValue}
                          onChange={setBroadcastingIntervalValue}
                        />
                        <Select
                          label="Broadcasting Day"
                          options={Array.from({ length: 31 }, (_, i) => ({ label: `${i + 1}`, value: `${i + 1}` }))}
                          value={selectedDayForBroadcasting}
                          onChange={setSelectedDayForBroadcasting}
                          helpText="Day of the month to broadcast"
                        />
                        <TextField
                          label="Schedule Time"
                          type="time"
                          value={scheduledOnTime}
                          onChange={setScheduledOnTime}
                        />
                      </FormLayout.Group>
                    </FormLayout>
                    <Banner tone="info">
                      <Text variant="bodyMd" as="p">
                        <strong>Note:</strong> Last order customer data lists will be calculated on every Broadcasting Day
                      </Text>
                    </Banner>
                  </BlockStack>
                </BlockStack>
              </Card>
            )}

            {/* Bottom Action Bar */}
            <Card>
              <InlineStack align="end">
                <ButtonGroup>
                  <Button onClick={handleCancel} disabled={updatingTrigger}>Cancel</Button>
                  <Button variant="primary" onClick={handleSave} disabled={!isFormValid} loading={updatingTrigger}>
                    Update Trigger
                  </Button>
                </ButtonGroup>
              </InlineStack>
            </Card>
          </BlockStack>
        </Grid.Cell>

        {/* ---- RIGHT COLUMN: preview ---- */}
        <Grid.Cell columnSpan={{ xs: 6, sm: 6, md: 4, lg: 4, xl: 4 }}>
          <div style={{ position: 'sticky', top: '20px', alignSelf: 'flex-start', zIndex: 10 }}>
            <BlockStack gap="500">
              <Card>
                <BlockStack gap="400">
                  <Text variant="headingMd" as="h2">Message Preview</Text>
                  {messageTemplate ? (
                    <BlockStack gap="300">
                      <Text variant="bodySm" as="p">
                        {allTemplateOptions.find(t => t.id === selectedTemplateId || t.value === selectedTemplateId)?.label || templateInputValue || 'Selected Template'}
                      </Text>
                      <Card sectioned background="bg-surface-secondary">
                        <WhatsAppPreview
                          template={selectedTemplateData || messageTemplate}
                          variant="bubble"
                          maxWidth="280px"
                          mediaMapping={mediaMapping}
                        />
                      </Card>
                      <Text variant="bodySm" as="p" tone="subdued">
                        Variables like {`{{customer_name}}`} will be replaced with actual data when sent.
                      </Text>
                    </BlockStack>
                  ) : (
                    <BlockStack gap="200">
                      <Text as="p" tone="subdued">Select a template to see the preview</Text>
                      <LegacyCard sectioned>
                        <Text variant="bodySm" as="p" tone="subdued">
                          Your message preview will appear here once you select a template.
                        </Text>
                      </LegacyCard>
                    </BlockStack>
                  )}
                </BlockStack>
              </Card>
            </BlockStack>
          </div>
        </Grid.Cell>
      </Grid>
    </Page>
  );
}

export default EditTriggerPage;
