export interface ProductTemplate {
  id: string;
  name: string;
  description: string;
  type: 'title' | 'pricing' | 'custom_label' | 'complete';
  titlePattern: string;
  descriptionPattern: string;
  priceRule: 'compare_at_and_price' | 'price_only' | 'compare_at_only';
  customLabels: {
    label0?: string;
    label1?: string;
    label2?: string;
    label3?: string;
    label4?: string;
  };
  badgeText?: string;
  isDefault?: boolean;
}

export const DEFAULT_TEMPLATES: ProductTemplate[] = [
  {
    id: 'tpl_advantage_plus',
    name: 'Advantage+ Dynamic Ad Standard',
    description: 'Clean product & variant title formatting with automated compare-at discount sale pricing for Facebook & Instagram carousel ads.',
    type: 'complete',
    titlePattern: '{{product.title}} - {{variant.title}} | {{product.vendor}}',
    descriptionPattern: '{{product.description}} Available in multiple sizes and colors. Fast worldwide shipping.',
    priceRule: 'compare_at_and_price',
    customLabels: {
      label0: 'InStock',
      label1: '{{product.product_type}}',
      label2: 'AdvantagePlus',
    },
    badgeText: 'Most Popular',
    isDefault: true,
  },
  {
    id: 'tpl_flash_sale',
    name: 'Flash Sale & Discount Badging',
    description: 'Highlights discount percentages directly in product titles to maximize click-through rates during sales promotions.',
    type: 'pricing',
    titlePattern: '🔥 [{{discount_percent}}% OFF] {{product.title}} ({{variant.title}})',
    descriptionPattern: 'LIMITED TIME DEAL: Save {{discount_amount}} on {{product.title}}! {{product.description}}',
    priceRule: 'compare_at_and_price',
    customLabels: {
      label0: 'SaleItem',
      label1: '{{discount_percent}}% OFF',
      label2: 'HighDiscount',
    },
    badgeText: 'High CTR',
    isDefault: false,
  },
  {
    id: 'tpl_spec_sku',
    name: 'Variant SKU & Technical Specs',
    description: 'Includes SKU code and variant option names for electronics, apparel, and hardware catalogs.',
    type: 'title',
    titlePattern: '{{product.vendor}} {{product.title}} - {{variant.title}} [SKU: {{variant.sku}}]',
    descriptionPattern: '{{product.description}} - Authentic {{product.vendor}} product. SKU: {{variant.sku}}.',
    priceRule: 'price_only',
    customLabels: {
      label0: 'TechSpec',
      label1: '{{product.vendor}}',
    },
    badgeText: 'Technical',
    isDefault: false,
  },
  {
    id: 'tpl_brand_hierarchy',
    name: 'Brand & Category Hierarchy',
    description: 'Optimized for large multi-category inventory stores to align with Google & Meta shopping tax classification.',
    type: 'custom_label',
    titlePattern: '{{product.vendor}} - {{product.title}}',
    descriptionPattern: '{{product.description}} Explore more in {{product.product_type}} at {{product.vendor}}.',
    priceRule: 'compare_at_and_price',
    customLabels: {
      label0: '{{product.vendor}}',
      label1: '{{product.product_type}}',
      label2: 'TopCategory',
      label3: 'Trending',
    },
    badgeText: 'Multi-Brand',
    isDefault: false,
  },
];

export const VARIABLE_TAGS = [
  { tag: '{{product.title}}', label: 'Product Title', sample: 'Alpine Snowboard Pro' },
  { tag: '{{product.vendor}}', label: 'Brand / Vendor', sample: 'Horizon Sports' },
  { tag: '{{product.product_type}}', label: 'Product Type', sample: 'Snowboards' },
  { tag: '{{variant.title}}', label: 'Variant Name', sample: '156cm / Cyan' },
  { tag: '{{variant.sku}}', label: 'Variant SKU', sample: 'SNOW-156-CYN' },
  { tag: '{{variant.price}}', label: 'Current Price', sample: '$249.00' },
  { tag: '{{variant.compare_at_price}}', label: 'Original Price', sample: '$349.00' },
  { tag: '{{discount_percent}}', label: 'Discount %', sample: '29' },
  { tag: '{{discount_amount}}', label: 'Discount $', sample: '$100.00' },
];

const STORAGE_KEY = 'meta_product_templates';

export function loadAllTemplates(): ProductTemplate[] {
  if (typeof window === 'undefined') {
    return DEFAULT_TEMPLATES;
  }
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return DEFAULT_TEMPLATES;
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed) && parsed.length > 0) {
      // Ensure default templates exist if not present
      const combined = [...parsed];
      DEFAULT_TEMPLATES.forEach(def => {
        if (!combined.some(t => t.id === def.id)) {
          combined.unshift(def);
        }
      });
      return combined;
    }
  } catch (e) {
    console.warn('Failed to parse templates from localStorage', e);
  }
  return DEFAULT_TEMPLATES;
}

export function saveAllTemplates(templates: ProductTemplate[]) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(templates));
    // Dispatch a custom storage event so other open pages/tabs update in real-time
    window.dispatchEvent(new Event('templates_updated'));
  } catch (e) {
    console.error('Failed to save templates to localStorage', e);
  }
}
