export interface HelpArticle {
  slug: string;
  title: string;
  subtitle: string;
  category: 'Getting Started' | 'Tracking & CAPI' | 'Analytics & Reports' | 'Billing & Plans' | 'Security & Optimization' | 'Compliance & Consent';
  badge?: string;
  readingTime: string;
  updatedAt: string;
  icon: string;
  summary: string;
  appDeepLink?: {
    href: string;
    label: string;
  };
  sections: Array<{
    id: string;
    title: string;
    content: string; // Markdown / HTML formatted
    callout?: {
      type: 'tip' | 'note' | 'warning' | 'important';
      text: string;
    };
    table?: {
      headers: string[];
      rows: string[][];
    };
    steps?: Array<{
      stepNumber: number;
      title: string;
      description: string;
    }>;
  }>;
  relatedArticleSlugs: string[];
  faqs?: Array<{
    question: string;
    answer: string;
  }>;
}

export const HELP_ARTICLES: HelpArticle[] = [
  {
    slug: 'pricing-plans',
    title: 'Pricing Plans & Quota Limits',
    subtitle: 'Choose the plan that best fits your business size, product catalog, and multi-pixel scaling needs.',
    category: 'Billing & Plans',
    badge: 'Official Guide',
    readingTime: '4 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-credit-card',
    summary: 'Detailed matrix of Free, Growth, and Scale tiers based on your Shopify plan and product quota, including multi-pixel limits, CAPI, Catalog sync frequencies, and audience sync.',
    appDeepLink: {
      href: '/pricing',
      label: 'View Pricing & Switch Plan',
    },
    sections: [
      {
        id: 'pricing-matrix',
        title: 'Shopify Plan & Quota Matrix',
        content: `Our pricing scales naturally with your Shopify store tier and the size of your product catalog. Below is the monthly price schedule across store tiers:`,
        table: {
          headers: ['Shopify Plan', 'Products Quota', 'Free Plan', 'Growth Plan', 'Scale Plan'],
          rows: [
            ['Basic / Grow', '100 SKUs', '$0.00 / mo', '$20.99 / mo', '—'],
            ['Basic / Grow', '1,000 SKUs', '—', '$25.99 / mo', '—'],
            ['Basic / Grow', '5,000 SKUs', '—', '$29.99 / mo', '—'],
            ['Basic / Grow', 'Unlimited SKUs', '—', '—', '$49.99 / mo'],
            ['Advanced', '100 SKUs', '$0.00 / mo', '$35.99 / mo', '—'],
            ['Advanced', '1,000 SKUs', '—', '$45.99 / mo', '—'],
            ['Advanced', '5,000 SKUs', '—', '$55.99 / mo', '—'],
            ['Advanced', 'Unlimited SKUs', '—', '—', '$79.99 / mo'],
            ['Shopify Plus', '100 SKUs', '$0.00 / mo', '$45.99 / mo', '—'],
            ['Shopify Plus', '1,000 SKUs', '—', '$55.99 / mo', '—'],
            ['Shopify Plus', '5,000 SKUs', '—', '$65.99 / mo', '—'],
            ['Shopify Plus', 'Unlimited SKUs', '—', '—', '$99.99 / mo'],
          ],
        },
        callout: {
          type: 'tip',
          text: 'Annual billing discount: Pay yearly to save 20% across all paid plans ($201.50/yr for Basic Growth, $345.50/yr for Advanced Growth). All paid plans come with a 7-day free trial.',
        },
      },
      {
        id: 'features-breakdown',
        title: 'What is Included in Each Plan?',
        content: `Compare all core tracking, Catalog feed sync, analytics, and reporting features side by side:`,
        table: {
          headers: ['Pricing & Features', 'Free', 'Growth', 'Scale'],
          rows: [
            ['Meta Pixel Count', '1 Pixel', 'Unlimited Pixels', 'Unlimited Pixels'],
            ['Conversion API (CAPI)', '1 Dataset', '1 Dataset (+$5.99/mo per extra)', 'Unlimited CAPI Datasets'],
            ['Order Tracking', '5 orders / month', 'Unlimited Orders', 'Unlimited Orders'],
            ['Advanced Tracking Rules', '✓ Included', '✓ Included', '✓ Included'],
            ['Specific-Market Pixel Routing', '—', '—', '✓ Included (Multi-Country)'],
            ['Catalog Feeds', '1 Feed', '3 Feeds', 'Unlimited Feeds'],
            ['Products for Catalog Feed', 'Up to 100 SKUs', '100 to 5,000 SKUs', 'Unlimited SKUs'],
            ['Catalog Sync Frequency', 'Basic (Sync weekly)', 'Standard (Sync daily)', 'Advanced (Sync daily + Real-time webhook)'],
            ['Order Report & Reconciliation', '✓ Included', '✓ Included', '✓ Included'],
            ['Pixel Analytics & Diagnostics', 'Basic Overview', 'Full Advanced Analytics', 'Full Advanced Analytics'],
            ['Event Activities Log', '—', '✓ Live Stream', '✓ Live Stream'],
            ['Real-Time Ads Report & UTMs', '—', '✓ Included', '✓ Included'],
            ['Audience Report: Who Buys, Who Returns', '✓ Included', '✓ Included', '✓ Included'],
            ['Bot & Fraud Protection', 'Layer 1 (Verified)', 'Layer 1 + Layer 2 (Blocking)', 'Layer 1 + Layer 2 + Auto-Recovery'],
            ['Restricted Mode (Consent)', '—', '—', '✓ Included'],
            ['Meta Audiences Creation', '—', '—', '✓ Lookalikes & Custom Audiences'],
            ['Customer Support', '24/7 Support', '24/7 Priority Chat & Email', 'Highest Priority 24/7 + VIP Community'],
          ],
        },
      },
      {
        id: 'how-to-switch',
        title: 'How to Switch or Upgrade Your Plan',
        content: `You can upgrade, downgrade, or customize your plan at any time directly through the app interface:`,
        steps: [
          {
            stepNumber: 1,
            title: 'Navigate to Pricing',
            description: 'Click "Pricing & Plans" in the main navigation or header.',
          },
          {
            stepNumber: 2,
            title: 'Select Plan & Billing Interval',
            description: 'Choose your desired tier (Free, Growth, or Scale) and select monthly or annual billing.',
          },
          {
            stepNumber: 3,
            title: 'Approve via Shopify Billing',
            description: 'You will be securely redirected to Shopify Admin Billing to approve the recurring application charge.',
          },
          {
            stepNumber: 4,
            title: 'Instant Synchronization',
            description: 'Your store entitlements, SKU quotas, and multi-pixel limits update immediately with zero downtime.',
          },
        ],
      },
    ],
    relatedArticleSlugs: [
      'setup-pixel-and-capi',
      'app-checklist',
      'advanced-settings',
      'ads-report',
      'audience-report',
      'consent-tracking',
    ],
    faqs: [
      {
        question: 'Will I be charged during the 7-day free trial?',
        answer: 'No. You have full access to all Growth or Scale features for 7 days without being billed. You can cancel at any time within your Shopify admin.',
      },
      {
        question: 'What happens if my store exceeds the product SKU quota?',
        answer: 'Your catalog feed will sync up to your plan limit. You will receive an in-app notice inviting you to adjust your tier or request a custom quota.',
      },
      {
        question: 'Can I add extra Conversions API tokens?',
        answer: 'Yes. Growth plans include 1 primary CAPI dataset and allow adding extra datasets for +$5.99/month each. Scale plans include unlimited CAPI datasets.',
      },
    ],
  },
  {
    slug: 'setup-pixel-and-capi',
    title: 'Setup Pixel and CAPI',
    subtitle: 'Step-by-step setup guide to connect your Meta Pixel ID and Conversions API access token to Shopify.',
    category: 'Getting Started',
    badge: 'Core Setup',
    readingTime: '3 min read',
    updatedAt: 'October 2026',
    icon: 'fa-brands fa-facebook',
    summary: 'Configure your Meta Pixel and server-side Conversions API in 3 simple steps: connect your Pixel ID, generate and paste your CAPI token, and activate the Shopify App Embed.',
    appDeepLink: {
      href: '/pixel?onboarding=true',
      label: 'Open Setup Wizard',
    },
    sections: [
      {
        id: 'overview-steps',
        title: '3-Step Setup Overview',
        content: `To start sending rich, deduplicated website traffic to Meta, follow our 3 guided setup steps:
1. **Step 1:** Give the Meta Pixel ID to the app (via Auto Connect with Facebook or Manual Input).
2. **Step 2:** Fill in the Conversions API (CAPI) access token and verify token health.
3. **Step 3:** Activate the Shopify Theme App Embed to enable browser tracking.`,
      },
      {
        id: 'step-1-pixel-id',
        title: 'Step 1: Provide Meta Pixel ID',
        content: `You can connect your Pixel using either **Auto Input** or **Manual Input**:
- **Auto Input (Recommended):** Click "Continue with Facebook". Log in and select your Meta Business Portfolio and Pixel Dataset. All asset IDs and names populate automatically without typo risk.
- **Manual Input:** If you cannot grant Facebook admin OAuth access, simply copy your 15–16 digit Pixel ID from Meta Events Manager and paste it into the Manual Input field.`,
        callout: {
          type: 'important',
          text: 'Dual-Source Input Management: The app protects you from accidental overwrites. If both Auto and Manual inputs are detected, you will see a side-by-side conflict dialog allowing you to explicitly choose which value to preserve.',
        },
      },
      {
        id: 'step-2-capi-token',
        title: 'Step 2: Fill in the CAPI Access Token',
        content: `A Conversions API access token allows our cloud server to transmit purchase and checkout events directly to Meta's Graph API, bypassing ad-blockers and iOS restrictions:
1. Copy your system user token or dataset token from Meta Events Manager.
2. Paste it into the **CAPI Access Token** field.
3. Click **Verify Token**. The app immediately pings Meta Graph API (\`graph.facebook.com/v22.0/me\`) to confirm that the token is valid, active, and holds the required \`ads_management\` permissions.
4. Optional: Fill in your Meta **Test Event Code** (e.g. \`TEST12345\`) to watch live events appear in Events Manager Test Events tab.`,
      },
      {
        id: 'step-3-app-embed',
        title: 'Step 3: Activate the Theme App Embed',
        content: `Browser tracking requires the Shopify Theme App Embed to be toggled ON in your active theme editor:
1. Click the **Activate in Theme Editor** button in Step 3.
2. A new tab opens your Shopify Customizer directly on the **App Embeds** tab with the app toggle highlighted.
3. Ensure the toggle is switched **ON** and click **Save** in the top-right corner.
4. Return to the app and click **Verify App Embed**. The app verifies your live storefront script tag and marks your setup complete.`,
        callout: {
          type: 'tip',
          text: 'Never insert manual <script> fbq() tags into theme.liquid. The App Embed handles standard events, custom DOM triggers, parameter enrichment, and server-side deduplication keys (event_id) automatically.',
        },
      },
    ],
    relatedArticleSlugs: [
      'how-to-generate-capi-access-token',
      'app-checklist',
      'advanced-settings',
      'bot-fraud-protection',
      'consent-tracking',
    ],
    faqs: [
      {
        question: 'Do I need both Browser Pixel and Conversions API?',
        answer: 'Yes! Combining Browser Pixel + CAPI provides redundant coverage. Meta automatically deduplicates matching events using the unique event_id generated by our engine, maximizing Event Match Quality (EMQ).',
      },
      {
        question: 'Can I route different Shopify markets or countries to different Pixels?',
        answer: 'Yes. On the Scale plan, you can add multiple Meta Pixels and designate specific countries or target collections for each pixel.',
      },
    ],
  },
  {
    slug: 'how-to-generate-capi-access-token',
    title: 'How to Generate Meta CAPI Access Token',
    subtitle: 'Visual walkthrough to generate a Conversions API access token in Meta Events Manager.',
    category: 'Getting Started',
    badge: 'Meta Walkthrough',
    readingTime: '3 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-key',
    summary: 'Step-by-step instructions with Meta Events Manager navigation to generate a long-lived Conversions API access token.',
    appDeepLink: {
      href: '/pixel?step=2',
      label: 'Paste Token in App',
    },
    sections: [
      {
        id: 'where-to-find-token',
        title: 'Generating Token in Meta Events Manager',
        content: `To enable server-side tracking, Meta requires a secure access token associated with your dataset:`,
        steps: [
          {
            stepNumber: 1,
            title: 'Open Meta Events Manager',
            description: 'Navigate to business.facebook.com/events_manager2 and select your Meta Business Account.',
          },
          {
            stepNumber: 2,
            title: 'Select Your Dataset / Pixel',
            description: 'In the left sidebar under "Data Sources", click on your Dataset or Pixel name.',
          },
          {
            stepNumber: 3,
            title: 'Go to Settings Tab',
            description: 'Click the "Settings" tab located along the top horizontal navigation bar.',
          },
          {
            stepNumber: 4,
            title: 'Scroll to Conversions API > Set up direct integration',
            description: 'Scroll down to the Conversions API section and find "Set up direct integration".',
          },
          {
            stepNumber: 5,
            title: 'Select "Set up with Dataset Quality API [Recommended]"',
            description: 'Choose "Set up with Dataset Quality API [Recommended]" and click "Generate access token". Generating this token enables real-time Event Match Quality metrics and direct event reporting.',
          },
          {
            stepNumber: 6,
            title: 'Copy & Paste into App',
            description: 'Copy the generated token string (starts with EAAdAd... or EAA...) and paste it into Step 2 of our setup wizard.',
          },
        ],
        callout: {
          type: 'important',
          text: 'Notice: Facebook App login tokens (starts with EAGR...) are account authentication tokens only and cannot deliver Conversions API events. Always generate a direct integration Dataset Quality API token (starts with EAA...).',
        },
      },
    ],
    relatedArticleSlugs: [
      'setup-pixel-and-capi',
      'app-checklist',
      'advanced-settings',
    ],
    faqs: [
      {
        question: 'Why do I see "You do not have permission to generate access token"?',
        answer: 'You must have Admin access (Full Control) over the Meta Business Portfolio and the Dataset. Contact your Business Manager administrator to grant you admin permissions.',
      },
    ],
  },
  {
    slug: 'app-checklist',
    title: 'App Setup Checklist & Troubleshooting',
    subtitle: 'Ensure your tracking setup is 100% accurate, prevent duplicate events, and verify timezone alignment.',
    category: 'Getting Started',
    badge: 'Checklist',
    readingTime: '4 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-list-check',
    summary: 'Follow this 3-point checklist to guarantee clean ad attribution: 1. Enable App Embed, 2. Match Timezone to Meta Ads, 3. Disconnect legacy and duplicate pixel scripts.',
    appDeepLink: {
      href: '/settings',
      label: 'Open Settings Checklist',
    },
    sections: [
      {
        id: 'item-1-app-embed',
        title: '1. Verify App Embed is Enabled',
        content: `Your events cannot fire in the shopper's browser unless the Theme App Embed is toggled ON:
- Go to Shopify Admin → Online Store → Themes → Customize.
- In the left panel, click the **App Embeds** icon (third tab).
- Ensure the app toggle is turned **ON** and click **Save**.
- If the embed is OFF, browser events will fail to trigger, and only server orders will be recorded.`,
      },
      {
        id: 'item-2-timezone',
        title: '2. Define and Match Timezones',
        content: `Always align the app's reporting timezone with your Meta Ads Account timezone:
- Go to **Settings → General** in the app.
- Select your primary advertising timezone (e.g., *America/New_York (GMT -05:00)* or *Asia/Kolkata (GMT +05:30)*).
- **Why this matters:** When timezones differ between your Shopify store and Meta Ads Manager, daily order numbers near midnight will appear in different calendar days, causing discrepancies in day-to-day ROAS attribution.`,
        callout: {
          type: 'warning',
          text: 'Mismatched timezones cause today\'s figures to look delayed or shifted by a few hours. Fully closed date ranges (e.g. Last 7 Days or Last Month) will reconcile accurately.',
        },
      },
      {
        id: 'item-3-duplicate-pixels',
        title: '3. Disconnect Duplicate & Legacy Pixels',
        content: `**Never track the same Pixel ID in multiple places.** Running the same Pixel ID in our app and another app causes duplicate page views, double-counted purchases, inflated revenue, and erratic ad delivery.
Check and remove the Pixel from these common duplicate locations:
1. **Shopify Native Facebook Sales Channel:** If connected to the same Pixel, disconnect it or disable tracking.
2. **Shopify Preferences:** Shopify Admin → Online Store → Preferences → Facebook Pixel section.
3. **Google Tag Manager (GTM):** Check if any Meta Pixel tags are active in your GTM container.
4. **Theme Code (theme.liquid):** Inspect your theme code for old hardcoded \`fbq('init', '...')\` snippets and remove them.`,
      },
    ],
    relatedArticleSlugs: [
      'setup-pixel-and-capi',
      'advanced-settings',
      'bot-fraud-protection',
      'ads-report',
    ],
  },
  {
    slug: 'advanced-settings',
    title: 'Advanced Settings: Fine-Tune Which Events We Send',
    subtitle: 'Customize event logic for Cash on Delivery (COD), subscription renewals, and bundle apps.',
    category: 'Tracking & CAPI',
    badge: 'Optimization',
    readingTime: '5 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-sliders',
    summary: 'Send cleaner, high-integrity signals to Meta by excluding recurring subscriptions, delaying COD purchases until fulfillment, and consolidating product bundle cart events.',
    appDeepLink: {
      href: '/settings#advanced',
      label: 'Configure Advanced Tracking',
    },
    sections: [
      {
        id: 'why-advanced-matters',
        title: 'Why Fine-Tuning Events Matters',
        content: `Every business model is different. Sending raw, unfiltered events can distort Meta's algorithmic optimization. Advanced Tracking lets you send only the signals that reflect real commercial value so Meta spends your ad budget on customers who actually pay.`,
      },
      {
        id: 'rule-1-subscriptions',
        title: '1. Exclude Subscription Recurring Orders',
        content: `For stores running subscription models (e.g. Recharge, Appstle, Skio):
- **How it works:** Only the **first order** of a subscription is sent as a Purchase event. All subsequent recurring renewals are filtered out.
- **Why use it:** Your ad campaigns earned the initial subscriber acquisition. Repeated monthly renewals inflate your ROAS with revenue your ads didn't actively generate.`,
        callout: {
          type: 'tip',
          text: 'Keeps your Customer Acquisition Cost (CAC) and ROAS realistic in Meta Ads Manager.',
        },
      },
      {
        id: 'rule-2-cod',
        title: '2. Send Purchase on Payment or Fulfillment (COD)',
        content: `For stores offering **Cash on Delivery (COD)** or pay-later checkout:
- Instead of firing a Purchase event the second an unconfirmed order is placed, the app holds the event until the order is **marked Paid** or **Fulfilled**.
- Orders cancelled, refused, or returned before delivery are never sent to Meta.
- Prevents Meta from optimizing toward fake orders or non-paying shoppers.`,
      },
      {
        id: 'rule-3-bundles',
        title: '3. Add to Cart Rules for Bundles',
        content: `When shoppers use bundle builder apps (Kaching, Wide Bundles, Moon Bundles, Fast Bundle), adding a 3-item bundle typically triggers 3 separate Add to Cart events in one click, inflating your funnel metrics.
You can choose from 3 counting rules:
1. **One event per product (Default):** Every cart item sends its own event.
2. **One event for the whole bundle (Recommended for ROAS):** Everything added in that click is consolidated into a single Add to Cart event worth the entire bundle price.
3. **One event, only the main product:** Only the product on the page being viewed is sent (ideal for catalog retargeting).
- **Bonus Option:** Toggle "Skip $0 items" to exclude free gifts and sample items from event totals.`,
      },
    ],
    relatedArticleSlugs: [
      'pricing-plans',
      'app-checklist',
      'bot-fraud-protection',
      'ads-report',
    ],
  },
  {
    slug: 'bot-fraud-protection',
    title: 'Protect Ad Data with Bot & Fraud Protection',
    subtitle: 'Filter automated web crawlers and suspicious fake orders to preserve ad delivery efficiency.',
    category: 'Security & Optimization',
    badge: 'Fraud Shield',
    readingTime: '4 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-shield-halved',
    summary: 'Prevent search bots, AI scrapers, and malicious scripts from muddying your Meta datasets and distorting your campaign learning phases.',
    appDeepLink: {
      href: '/settings#bot-protection',
      label: 'Configure Bot Protection',
    },
    sections: [
      {
        id: 'why-bot-protection',
        title: 'Why Bot Traffic Hurts Your Ad ROAS',
        content: `Meta's machine learning optimizes bids based on the conversion events it receives. When bots trigger fake PageViews, AddToCarts, or unfulfilled purchases:
1. **Inflated Audience Sizes:** Bot visits pollute your custom website traffic audiences.
2. **Misguided Algorithm Learning:** Fake purchase events with fabricated values teach Meta the wrong buyer profiles, driving ad budget into worthless traffic.`,
      },
      {
        id: 'layer-1-filtering',
        title: 'Layer 1: Verified Bot Filtering (Automatic)',
        content: `Automatically detects and excludes visits from known, legitimate web crawlers such as:
- Search engines (Googlebot, Bingbot, Yandex, DuckDuckBot)
- Social media preview scrapers (Facebook External Hit, Twitterbot, LinkedInBot)
- AI indexing agents (ChatGPT-User, Claude-Web, PerplexityBot)
- **Always Active:** This layer is enabled by default with zero configuration required. Real shoppers are never blocked.`,
      },
      {
        id: 'layer-2-blocking',
        title: 'Layer 2: Suspicious Bot & Fraud Blocking',
        content: `Goes deeper by analyzing request signatures, headless browser markers, automation headers (Puppeteer, Selenium, headless Chrome), and rapid-fire API spam.
- Suspicious events are intercepted and placed into a **Held Queue**.
- In **Tracking Analytics → Bot & Fraud**, you can inspect held events, review the detection reason, IP, country, and Shopify order ID, and manually click **Resend to Meta** if an event was genuine.`,
        callout: {
          type: 'important',
          text: 'Available on Growth and Scale plans. Gives you total auditability with zero false-positive risk.',
        },
      },
    ],
    relatedArticleSlugs: [
      'advanced-settings',
      'consent-tracking',
      'ads-report',
      'pricing-plans',
    ],
  },
  {
    slug: 'consent-tracking',
    title: 'Consent Tracking & Restricted Mode (GDPR/ePrivacy)',
    subtitle: 'Understand consent policy impacts on Meta events and how Restricted Mode maintains server attribution.',
    category: 'Compliance & Consent',
    badge: 'GDPR / Privacy',
    readingTime: '5 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-user-shield',
    summary: 'When shoppers decline cookies, browser events are suppressed by law. Learn how our Consent Coverage report quantifies missing data and how Scale Restricted Mode works.',
    appDeepLink: {
      href: '/analytics#consent',
      label: 'View Consent Coverage',
    },
    sections: [
      {
        id: 'consent-overview',
        title: 'How Cookie Consent Affects Meta Tracking',
        content: `When a customer visits your store from regions requiring opt-in cookie consent (such as the EU, UK, or California) and clicks "Decline" on your cookie banner:
- By law, the browser Meta Pixel **must be blocked** from setting cookies or transmitting tracking tags.
- As a result, browser Add to Cart and Initiate Checkout events for that session will **not reach Meta**.
- **Purchase Tracking is Protected:** Because Purchase is recorded server-side from Shopify order records, your revenue data is never lost. Only the top-of-funnel conversion rate appears artificially lower in Ads Manager.`,
      },
      {
        id: 'coverage-report',
        title: 'The Consent Coverage Report',
        content: `Located under **Tracking Analytics → Consent Coverage**:
- **Missing from Meta:** Quantifies the exact number of top-funnel events suppressed due to cookie denial.
- **Funnel Visibility Score:** The percentage of total customer journey steps Meta is able to observe.
- **Market Consent Rates:** Breakdown by country highlighting where cookie opt-in rates are lowest (e.g. Germany, UK, France).`,
      },
      {
        id: 'restricted-mode',
        title: 'Restricted Mode (Scale Plan)',
        content: `On the **Scale Plan**, merchants can enable **Restricted Mode**:
- Transmits anonymized server-side event signals with stripped personal identifiers for shoppers who declined browser cookies.
- Helps Meta maintain campaign delivery models without violating client-side storage policies.
- Easily toggle ON/OFF in **Settings → Consent**.`,
        callout: {
          type: 'note',
          text: 'Legal Notice: Merchants are responsible for ensuring that their privacy policy and consent banner disclose server-side processing in accordance with local regulations.',
        },
      },
    ],
    relatedArticleSlugs: [
      'bot-fraud-protection',
      'ads-report',
      'pricing-plans',
      'app-checklist',
    ],
  },
  {
    slug: 'ads-report',
    title: 'Ads Report: Track Your Ad Performance in Real Time',
    subtitle: 'Compare Meta ad metrics and store-matched revenue side by side with live UTM attribution.',
    category: 'Analytics & Reports',
    badge: 'Real-Time ROI',
    readingTime: '5 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-chart-line',
    summary: 'Eliminate reporting blind spots by pairing Meta ad spend with real Shopify orders matched via UTM parameters, updating in near real-time.',
    appDeepLink: {
      href: '/ads-report',
      label: 'Open Ads Report',
    },
    sections: [
      {
        id: 'side-by-side',
        title: 'Two Data Sources in One Unified Workspace',
        content: `Stop jumping between Meta Ads Manager tabs and Shopify analytics. The Ads Report shows:
- **Meta Figures (Blue Dot):** Ad Spend, Impressions, Link Clicks, Meta-reported Purchases, and CPM straight from Meta Ads API.
- **Store-Matched Figures (Purple Dot):** Actual Shopify revenue, verified purchases, Customer Acquisition Cost (CAC), and Average Order Value (AOV) attributed directly via last-click UTM.
- **True ROAS:** Calculated as *(Verified Shopify Store Revenue ÷ Meta Ad Spend)*.`,
      },
      {
        id: 'utm-coverage',
        title: 'UTM Parameters & Coverage Indicator',
        content: `UTMs are how the app connects orders back to the exact winning ad:
- Copy the default UTM string from the app:
\`utm_source=facebook&utm_medium=paid&utm_campaign={{campaign.name}}&utm_content={{ad.name}}&utm_term={{adset.name}}&fb_ad_id={{ad.id}}\`
- Paste it into the **URL parameters** box in Meta Ads Manager when creating or editing your ad.
- The **UTM Coverage Indicator** shows the percentage of active ads carrying valid UTM tracking. Aim for 100% coverage to avoid unmeasurable ad spend.`,
        callout: {
          type: 'tip',
          text: 'Orders placed from ads without UTM parameters appear with "No UTM" badges and cannot be mapped to individual ad sets.',
        },
      },
      {
        id: 'order-reconciliation',
        title: 'Order Reconciliation: Explaining the Data Gap',
        content: `Why do Meta purchases rarely match Shopify order totals?
1. **Ad Blocker / Cookie Opt-Out:** Some shoppers refuse cookies; server CAPI captures the order while Meta Ads Manager attribution window may delay crediting.
2. **7-Day Attribution Windows:** Meta credits purchases up to 7 days after the click, causing historical retrospective adjustment.
3. **Cross-Device Journeys:** Customers clicking on mobile but checking out on desktop hours later. Our reconciliation cards explain the exact variance.`,
      },
    ],
    relatedArticleSlugs: [
      'audience-report',
      'advanced-settings',
      'setup-pixel-and-capi',
      'pricing-plans',
    ],
  },
  {
    slug: 'audience-report',
    title: 'Audience Report: Understand Who Your Customers Are',
    subtitle: 'Analyze customer purchase cycles and sync high-converting custom & lookalike audiences to Meta.',
    category: 'Analytics & Reports',
    badge: 'Customer Intelligence',
    readingTime: '5 min read',
    updatedAt: 'October 2026',
    icon: 'fa fa-users',
    summary: 'View repeat purchase intervals, customer cohorts, device breakdown, and create 1-click Recent Buyers, Retargeting, and Lookalike audiences in Meta Ads Manager.',
    appDeepLink: {
      href: '/audiences',
      label: 'Explore Audiences',
    },
    sections: [
      {
        id: 'customer-overview',
        title: '1. Customer Overview & Cohorts',
        content: `Four top-level metrics summarize your shopper base:
- **Total Unique Customers:** Real people who completed at least one order.
- **Revenue per Customer:** Average customer lifetime revenue.
- **Repeat Buyer Rate:** Share of customers who placed 2 or more orders.
- **From Meta Ads:** Percentage of buyers whose journey originated from Meta ad campaigns.`,
      },
      {
        id: 'repeat-intervals',
        title: '2. Repeat Purchase Intervals & Timing',
        content: `Know exactly when returning customers make their second order:
- **0–30 Days, 31–60 Days, 61–90 Days:** Visual bars show when repeat purchases cluster.
- **Median Time to 2nd Order:** Use this number to set your retargeting and email flow delays (e.g. if the median is 42 days, start your win-back ads around day 35).
- **Revenue from Repeat Buyers:** See how much of your store's total gross revenue is powered by loyal retention vs new acquisition.`,
      },
      {
        id: 'meta-audiences-sync',
        title: '3. One-Click Meta Audiences (Scale Plan)',
        content: `Create high-performing Meta audiences directly from the app without building manual CSV files or complex Ads Manager rules:`,
        table: {
          headers: ['Audience Type', 'Who is in it?', 'Strategic Campaign Use'],
          rows: [
            ['Recent Buyers', 'Customers who purchased within the last 7 to 180 days', 'Exclude from top-of-funnel acquisition ads to save budget'],
            ['Retarget Shoppers', 'Viewed product or added to cart but did not purchase', 'Serve compelling dynamic product ads to close abandoned carts'],
            ['High-Value Lookalike (1–20%)', 'Meta lookalike built from your top 5%, 10%, or 25% biggest spenders', 'Scale winning cold acquisition to find shoppers with high purchasing power'],
          ],
        },
        callout: {
          type: 'important',
          text: 'Audience memberships update automatically. When a shopper completes a purchase, Meta removes them from "Retarget Shoppers" and promotes them to "Recent Buyers" within hours.',
        },
      },
    ],
    relatedArticleSlugs: [
      'ads-report',
      'advanced-settings',
      'pricing-plans',
      'consent-tracking',
    ],
  },
];

export function getHelpArticle(slug: string): HelpArticle | undefined {
  return HELP_ARTICLES.find((article) => article.slug === slug);
}

export function getRelatedArticles(slugs: string[]): HelpArticle[] {
  return HELP_ARTICLES.filter((article) => slugs.includes(article.slug));
}
