/**
 * App Thread Intake Config
 *
 * Maps every MCP app ID to its intake question, skip behavior, and AI prompt addon.
 * When a user clicks an app bubble, if getAppIntake() returns non-null,
 * a conversational thread opens instead of immediately loading the app.
 *
 * Passthrough apps (return null) load immediately like before.
 */

export interface AppIntake {
  category: string;
  question: string;
  skipLabel?: string;       // If defined, user can skip the thread and load default data
  systemPromptAddon: string; // Extra AI instructions for generating APP_DATA
}

// ─── No more passthrough apps — everything uses threads ──────────────────────

// ─── Per-app intake configs ──────────────────────────────────────────────────

const APP_INTAKES: Record<string, AppIntake> = {
  // ═══════════════════════════════════════════════════════════════════════════
  // WORKFLOW BUILDER — "What do you want to automate?"
  // ═══════════════════════════════════════════════════════════════════════════

  "n8n-workflow-builder": {
    category: "workflow-builder",
    question: "What would you like to automate? Describe the workflow you want to build in plain language.",
    systemPromptAddon: `The user wants to build an n8n workflow. Generate an APP_DATA block with the workflow data so the visual builder updates.

Use this APP_DATA shape:
{
  "name": "Workflow Name",
  "nodes": [
    { "name": "Node Name", "type": "n8n-nodes-base.nodeType", "icon": "emoji", "category": "Triggers|Actions|Transform|Flow|AI", "parameters": { "key": "value" } }
  ],
  "requiredCredentials": [
    { "service": "ServiceName", "icon": "emoji", "type": "credential-type", "description": "What it does" }
  ]
}

Use real n8n node types:
  Triggers: n8n-nodes-base.webhook (🌐), n8n-nodes-base.scheduleTrigger (⏰), n8n-nodes-base.formTrigger (📝), n8n-nodes-base.manualTrigger (👆)
  Actions: n8n-nodes-base.httpRequest (🌍), n8n-nodes-base.slack (💬), n8n-nodes-base.gmail (📧), n8n-nodes-base.googleDrive (📁), n8n-nodes-base.googleSheets (📊)
  Transform: n8n-nodes-base.code (💻), n8n-nodes-base.set (✏️), n8n-nodes-base.if (🔀), n8n-nodes-base.switch (🔃), n8n-nodes-base.merge (🔗)
  Flow: n8n-nodes-base.wait (⏳), n8n-nodes-base.splitInBatches (🔁), n8n-nodes-base.errorTrigger (🚨)
  AI: @n8n/n8n-nodes-langchain.openAi (🧠), @n8n/n8n-nodes-langchain.agent (🤖)

Start every workflow with a trigger. Include sensible default parameters. Also write a clear natural language explanation of the workflow.`,
  },

  "n8n-execution-monitor": {
    category: "monitor",
    question: "Which workflow's execution history would you like to check? Or want to see all recent executions?",
    skipLabel: "All recent executions",
    systemPromptAddon: `The user is viewing workflow execution history. Show recent executions with status, timing, and error info.`,
  },

  "n8n-webhook-tester": {
    category: "search",
    question: "Which webhook would you like to test? Provide the webhook URL or workflow name.",
    systemPromptAddon: `The user wants to test a webhook endpoint. Help them configure and send test payloads.`,
  },

  "n8n-workflow-detail": {
    category: "detail",
    question: "Which workflow would you like to view the details for?",
    systemPromptAddon: `The user wants to see details of a specific workflow including nodes, connections, and settings.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // DASHBOARD CATEGORY — "What time frame would you like to see?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-location-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see for your location overview? (e.g., last 7 days, this month, last quarter)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Location Dashboard. Generate APP_DATA with a "timeFrame" field and optionally filtered metrics. The data shape should include: { timeFrame: string, metrics: { leads: number, appointments: number, revenue: number, ... }, trend: "up"|"down"|"flat" }`,
  },
  "ghl-revenue-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see for revenue? (e.g., last 7 days, this month, Q4 2025, year-to-date)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Revenue Dashboard. Generate APP_DATA with revenue figures for the requested time frame. Include: { timeFrame: string, totalRevenue: number, recurringRevenue: number, transactions: number, averageOrderValue: number }`,
  },
  "ghl-pipeline-analytics": {
    category: "dashboard",
    question: "What time frame would you like to analyze your pipeline? (e.g., this month, last quarter, custom range)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Pipeline Analytics. Generate APP_DATA with pipeline performance metrics for the requested period. Include stage conversion rates, deal velocity, and win/loss ratios.`,
  },
  "ghl-pipeline-funnel": {
    category: "dashboard",
    question: "Which pipeline's funnel would you like to visualize, and for what time period? (e.g., Sales pipeline, last 30 days)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Pipeline Funnel. Generate APP_DATA with funnel stages, counts at each stage, and conversion rates between stages.`,
  },
  "ghl-campaign-stats": {
    category: "dashboard",
    question: "Which campaigns would you like to see stats for? (e.g., all active, a specific campaign, last 30 days)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Campaign Stats. Generate APP_DATA with campaign performance data including sends, opens, clicks, conversions, and revenue attributed.`,
  },
  "ghl-agent-stats": {
    category: "dashboard",
    question: "Which time period would you like to see agent performance for? (e.g., today, this week, this month)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Agent Stats. Generate APP_DATA with per-agent metrics: calls made, emails sent, deals closed, response time, and customer satisfaction scores.`,
  },
  "ghl-reviews-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see reviews for? (e.g., last 30 days, this quarter, all-time)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Reviews Dashboard. Generate APP_DATA with review metrics: average rating, total reviews, sentiment breakdown, and recent review highlights.`,
  },
  "ghl-affiliate-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see affiliate performance for? (e.g., this month, last quarter)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Affiliate Dashboard. Generate APP_DATA with affiliate metrics: total referrals, conversions, revenue generated, top affiliates, and commission payouts.`,
  },
  "ghl-inventory-dashboard": {
    category: "dashboard",
    question: "What would you like to focus on in your inventory? (e.g., low stock items, specific categories, overall summary)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Inventory Dashboard. Generate APP_DATA with inventory metrics: total SKUs, low stock alerts, stock value, and category breakdowns.`,
  },
  "google-ads-campaign-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see your Google Ads campaigns for? (e.g., last 7 days, this month, last 90 days)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Google Ads Campaign Dashboard. Generate APP_DATA with campaign-level metrics: spend, clicks, impressions, CTR, CPC, conversions, ROAS for the requested time frame.`,
  },
  "google-ads-performance-overview": {
    category: "dashboard",
    question: "What time frame would you like for your Google Ads performance overview? (e.g., last 7 days, month-to-date, year comparison)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Google Ads Performance Overview. Generate APP_DATA with account-level KPIs: total spend, total conversions, average CPC, CTR, impression share, and daily trend data.`,
  },
  "meta-ads-campaign-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see your Meta ad campaigns for? (e.g., last 7 days, this month, compare to last month)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Meta Ads Campaign Dashboard. Generate APP_DATA with campaign metrics: spend, reach, impressions, CTR, CPC, CPM, conversions, and ROAS.`,
  },
  "meta-ads-performance-heatmap": {
    category: "dashboard",
    question: "What time frame and metric would you like to visualize in the heatmap? (e.g., last 7 days by CTR, this month by spend)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Meta Ads Performance Heatmap. Generate APP_DATA with hourly/daily performance data broken down by the requested metric for heatmap visualization.`,
  },
  "meta-ads-spend-tracker": {
    category: "dashboard",
    question: "What time frame would you like to track Meta ad spend for? (e.g., this month vs budget, last 90 days trend)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Meta Ads Spend Tracker. Generate APP_DATA with daily spend data, budget utilization, pacing, and projected month-end spend.`,
  },
  "meta-ads-ab-test-results": {
    category: "dashboard",
    question: "Which A/B tests would you like to review? (e.g., all active, a specific campaign, completed tests)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Meta Ads A/B Test Results. Generate APP_DATA with test variants, performance per variant, statistical significance, and recommendations.`,
  },
  "meta-ads-account-health": {
    category: "dashboard",
    question: "What aspects of your Meta ad account health would you like to review? (e.g., overall score, policy issues, performance alerts)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Meta Ads Account Health. Generate APP_DATA with health score, policy warnings, performance anomalies, and optimization recommendations.`,
  },
  "gsc-performance-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see your Search Console performance for? (e.g., last 28 days, last 3 months, compare periods)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the GSC Performance Dashboard. Generate APP_DATA with search metrics: total clicks, impressions, average CTR, average position, top queries, and top pages.`,
  },
  "twilio-dashboard": {
    category: "dashboard",
    question: "What time frame would you like to see your Twilio account overview for? (e.g., today, this week, this month)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Twilio Dashboard. Generate APP_DATA with account metrics: messages sent/received, calls made/received, active numbers, account balance, and usage trends.`,
  },
  "twilio-call-analytics": {
    category: "dashboard",
    question: "What time frame and metrics would you like to see for call analytics? (e.g., today's calls, this week by duration, this month by agent)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing Twilio Call Analytics. Generate APP_DATA with call metrics: total calls, average duration, call completion rate, peak hours, and per-agent breakdowns.`,
  },
  "twilio-cost-report": {
    category: "dashboard",
    question: "What time frame would you like to see Twilio costs for? (e.g., this month, last quarter, year-to-date)",
    skipLabel: "Last 30 days",
    systemPromptAddon: `The user is viewing the Twilio Cost Report. Generate APP_DATA with cost breakdowns: messaging costs, voice costs, number costs, total spend, daily trends, and projections.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // LIST CATEGORY — "How would you like to filter these?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-contact-grid": {
    category: "list",
    question: "How would you like to filter your contacts? (e.g., by tag, source, date added, search by name, or show VIP only)",
    skipLabel: "Show all contacts",
    systemPromptAddon: `The user is viewing the Contact Grid. Generate APP_DATA with filtered contact list. Shape: { filter: { description: string }, contacts: Array<{ id, firstName, lastName, email, phone, tags, dateAdded, source, companyName? }> }. Use realistic business contacts. Apply the user's filter criteria.`,
  },
  "ghl-company-list": {
    category: "list",
    question: "How would you like to filter your companies? (e.g., by industry, size, recent activity, or search by name)",
    skipLabel: "Show all companies",
    systemPromptAddon: `The user is viewing the Company List. Generate APP_DATA with filtered company list. Include: name, industry, employee count, contact person, last activity date.`,
  },
  "ghl-conversation-list": {
    category: "list",
    question: "Which conversations would you like to see? (e.g., unread only, by channel type, starred, or search by contact)",
    skipLabel: "Show all conversations",
    systemPromptAddon: `The user is viewing the Conversation List. Generate APP_DATA with filtered conversations. Include: contact name, last message preview, channel (SMS/email/chat), timestamp, read/unread status.`,
  },
  "ghl-invoice-list": {
    category: "list",
    question: "Filter invoices by status (paid, unpaid, overdue), date range, or client name?",
    skipLabel: "Show all invoices",
    systemPromptAddon: `The user is viewing the Invoice List. Generate APP_DATA with filtered invoices. Include: invoice number, client name, amount, status (paid/unpaid/overdue), due date, issue date.`,
  },
  "ghl-transaction-list": {
    category: "list",
    question: "Filter transactions by type (payment, refund), date range, amount, or client?",
    skipLabel: "Show all transactions",
    systemPromptAddon: `The user is viewing the Transaction List. Generate APP_DATA with filtered transactions. Include: transaction ID, type, amount, client, date, payment method, status.`,
  },
  "ghl-call-log": {
    category: "list",
    question: "Filter calls by date, duration, direction (inbound/outbound), or contact?",
    skipLabel: "Show all calls",
    systemPromptAddon: `The user is viewing the Call Log. Generate APP_DATA with filtered call records. Include: contact name, phone, direction, duration, timestamp, status (answered/missed/voicemail).`,
  },
  "ghl-order-list": {
    category: "list",
    question: "Filter orders by status (pending, fulfilled, cancelled), date, or customer?",
    skipLabel: "Show all orders",
    systemPromptAddon: `The user is viewing the Order List. Generate APP_DATA with filtered orders. Include: order number, customer, items count, total, status, date.`,
  },
  "ghl-form-list": {
    category: "list",
    question: "Which forms would you like to see? (e.g., active forms, by type, most submissions, or search by name)",
    skipLabel: "Show all forms",
    systemPromptAddon: `The user is viewing the Form List. Generate APP_DATA with filtered forms. Include: form name, type, submissions count, created date, status (active/inactive).`,
  },
  "ghl-form-submissions": {
    category: "list",
    question: "Which form's submissions would you like to see? Filter by date, status, or specific form?",
    skipLabel: "Show all submissions",
    systemPromptAddon: `The user is viewing Form Submissions. Generate APP_DATA with filtered submissions. Include: form name, submitter info, submission date, status, key field values.`,
  },
  "ghl-survey-list": {
    category: "list",
    question: "Which surveys would you like to see? (e.g., active, completed, by response count)",
    skipLabel: "Show all surveys",
    systemPromptAddon: `The user is viewing the Survey List. Generate APP_DATA with filtered surveys. Include: survey name, response count, completion rate, created date, status.`,
  },
  "ghl-survey-submissions": {
    category: "list",
    question: "Which survey's responses would you like to see? Filter by date, score, or specific survey?",
    skipLabel: "Show all responses",
    systemPromptAddon: `The user is viewing Survey Submissions. Generate APP_DATA with filtered survey responses. Include: respondent info, submission date, score/rating, key answers.`,
  },
  "ghl-funnel-list": {
    category: "list",
    question: "Which funnels would you like to see? (e.g., active, by conversion rate, by traffic source)",
    skipLabel: "Show all funnels",
    systemPromptAddon: `The user is viewing the Funnel List. Generate APP_DATA with filtered funnels. Include: funnel name, steps count, views, conversion rate, revenue, status.`,
  },
  "ghl-task-board": {
    category: "list",
    question: "How would you like to view your tasks? (e.g., by assignee, due date, priority, status, or overdue only)",
    skipLabel: "Show all tasks",
    systemPromptAddon: `The user is viewing the Task Board. Generate APP_DATA with filtered tasks. Include: task title, assignee, due date, priority (high/medium/low), status (todo/in-progress/done), associated contact.`,
  },
  "ghl-subscription-manager": {
    category: "list",
    question: "Filter subscriptions by status (active, cancelled, past due), plan, or customer?",
    skipLabel: "Show all subscriptions",
    systemPromptAddon: `The user is viewing the Subscription Manager. Generate APP_DATA with filtered subscriptions. Include: customer, plan name, amount, status, start date, next billing date.`,
  },
  "ghl-coupon-manager": {
    category: "list",
    question: "Which coupons would you like to see? (e.g., active, expired, by discount type, most used)",
    skipLabel: "Show all coupons",
    systemPromptAddon: `The user is viewing the Coupon Manager. Generate APP_DATA with filtered coupons. Include: code, discount (% or fixed), uses, expiry date, status, applicable products.`,
  },
  "ghl-product-catalog": {
    category: "list",
    question: "Filter products by category, price range, availability, or search by name?",
    skipLabel: "Show all products",
    systemPromptAddon: `The user is viewing the Product Catalog. Generate APP_DATA with filtered products. Include: name, price, category, stock status, image URL, description.`,
  },
  "ghl-course-catalog": {
    category: "list",
    question: "Which courses would you like to see? (e.g., published, draft, by enrollment count, by category)",
    skipLabel: "Show all courses",
    systemPromptAddon: `The user is viewing the Course Catalog. Generate APP_DATA with filtered courses. Include: title, category, enrollments, completion rate, status, price.`,
  },
  "ghl-social-calendar": {
    category: "list",
    question: "What date range and platforms would you like to see scheduled posts for? (e.g., this week, Instagram only, all platforms this month)",
    skipLabel: "Show all posts",
    systemPromptAddon: `The user is viewing the Social Calendar. Generate APP_DATA with filtered social posts. Include: post content preview, platform, scheduled date/time, status (scheduled/published/draft).`,
  },
  "ghl-blog-manager": {
    category: "list",
    question: "Which blog posts would you like to see? (e.g., published, drafts, by category, most viewed)",
    skipLabel: "Show all posts",
    systemPromptAddon: `The user is viewing the Blog Manager. Generate APP_DATA with filtered blog posts. Include: title, status (published/draft), author, publish date, views, category.`,
  },
  "ghl-media-library": {
    category: "list",
    question: "Filter media by type (images, videos, documents), date, or search by name?",
    skipLabel: "Show all media",
    systemPromptAddon: `The user is viewing the Media Library. Generate APP_DATA with filtered media items. Include: filename, type, size, upload date, thumbnail URL, used in (forms/funnels/etc).`,
  },
  "ghl-workflow-status": {
    category: "list",
    question: "Which workflows would you like to see? (e.g., active, paused, by trigger type, recently edited)",
    skipLabel: "Show all workflows",
    systemPromptAddon: `The user is viewing Workflow Status. Generate APP_DATA with filtered workflows. Include: name, status (active/paused/draft), trigger type, last run, executions count, error rate.`,
  },
  "ghl-smartlist-viewer": {
    category: "list",
    question: "Which smart list would you like to view? (e.g., by name, contact count, recently created)",
    skipLabel: "Show all smart lists",
    systemPromptAddon: `The user is viewing Smart Lists. Generate APP_DATA with smart list data. Include: list name, filter criteria, contact count, created date, last updated.`,
  },
  "ghl-tags-manager": {
    category: "list",
    question: "How would you like to view your tags? (e.g., most used, search by name, by category)",
    skipLabel: "Show all tags",
    systemPromptAddon: `The user is viewing the Tags Manager. Generate APP_DATA with tag data. Include: tag name, contact count, category, color, created date.`,
  },
  "ghl-template-library": {
    category: "list",
    question: "Which templates would you like to browse? (e.g., email, SMS, by category, most used)",
    skipLabel: "Show all templates",
    systemPromptAddon: `The user is viewing the Template Library. Generate APP_DATA with filtered templates. Include: name, type (email/SMS/voicemail), category, usage count, last modified.`,
  },
  "twilio-message-log": {
    category: "list",
    question: "Filter messages by direction (inbound/outbound), date, status (delivered/failed), or search by number?",
    skipLabel: "Show all messages",
    systemPromptAddon: `The user is viewing the Twilio Message Log. Generate APP_DATA with filtered messages. Include: from, to, body preview, status, direction, timestamp, cost.`,
  },
  "twilio-number-inventory": {
    category: "list",
    question: "Filter your phone numbers by capability (SMS, voice, MMS), area code, or status?",
    skipLabel: "Show all numbers",
    systemPromptAddon: `The user is viewing Twilio Number Inventory. Generate APP_DATA with phone numbers. Include: number, friendly name, capabilities (SMS/voice/MMS), status, monthly cost.`,
  },
  "twilio-flow-list": {
    category: "list",
    question: "Which Studio flows would you like to see? (e.g., active, by type, recently modified)",
    skipLabel: "Show all flows",
    systemPromptAddon: `The user is viewing Twilio Flow List. Generate APP_DATA with Studio flows. Include: flow name, status, type, last modified, execution count.`,
  },
  "twilio-error-log": {
    category: "list",
    question: "Filter errors by severity (warning/error/critical), date range, or error code?",
    skipLabel: "Show all errors",
    systemPromptAddon: `The user is viewing the Twilio Error Log. Generate APP_DATA with error records. Include: error code, severity, message, timestamp, resource affected, count.`,
  },
  "twilio-inbox": {
    category: "list",
    question: "Filter your inbox by status (unread, starred), channel (SMS/WhatsApp/chat), or search by contact?",
    skipLabel: "Show all messages",
    systemPromptAddon: `The user is viewing the Twilio Inbox. Generate APP_DATA with inbox conversations. Include: contact, channel, last message preview, timestamp, read/unread, starred.`,
  },
  "twilio-queue-manager": {
    category: "list",
    question: "Which queues would you like to see? (e.g., active, by wait time, by agent count)",
    skipLabel: "Show all queues",
    systemPromptAddon: `The user is viewing the Twilio Queue Manager. Generate APP_DATA with queue data. Include: queue name, current size, average wait time, agents assigned, status.`,
  },
  "meta-ads-ad-performance-grid": {
    category: "list",
    question: "Filter ads by campaign, status (active/paused), performance metric, or date range?",
    skipLabel: "Show all ads",
    systemPromptAddon: `The user is viewing the Meta Ads Ad Performance Grid. Generate APP_DATA with ad-level data. Include: ad name, campaign, status, spend, impressions, clicks, CTR, CPC, conversions.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // DETAIL CATEGORY — "Which [item] would you like to view?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-contact-card": {
    category: "detail",
    question: "Which contact would you like to view? (search by name, email, or phone number)",
    systemPromptAddon: `The user wants to view a specific contact's card. Generate APP_DATA with full contact details: name, email, phone, tags, source, company, all custom fields, notes, and recent activity.`,
  },
  "ghl-contact-timeline": {
    category: "detail",
    question: "Which contact's timeline would you like to view? (search by name, email, or phone)",
    systemPromptAddon: `The user wants to view a contact's timeline. Generate APP_DATA with the contact's full activity history: emails, calls, form submissions, appointments, notes, and tag changes.`,
  },
  "ghl-company-detail": {
    category: "detail",
    question: "Which company would you like to view? (search by name or industry)",
    systemPromptAddon: `The user wants to view company details. Generate APP_DATA with full company info: name, industry, size, contacts, deals, revenue, recent activity.`,
  },
  "ghl-opportunity-card": {
    category: "detail",
    question: "Which opportunity/deal would you like to view? (search by name, contact, or pipeline stage)",
    systemPromptAddon: `The user wants to view an opportunity. Generate APP_DATA with deal details: name, value, stage, contact, pipeline, expected close date, notes, and history.`,
  },
  "ghl-appointment-detail": {
    category: "detail",
    question: "Which appointment would you like to view? (search by contact name, date, or calendar)",
    systemPromptAddon: `The user wants to view appointment details. Generate APP_DATA with: title, contact, date/time, duration, calendar, status, notes, and reminders.`,
  },
  "ghl-invoice-preview": {
    category: "detail",
    question: "Which invoice would you like to preview? (search by invoice number, client, or amount)",
    systemPromptAddon: `The user wants to preview an invoice. Generate APP_DATA with full invoice: number, client, line items, subtotal, tax, total, status, payment terms, due date.`,
  },
  "ghl-estimate-preview": {
    category: "detail",
    question: "Which estimate would you like to preview? (search by client or estimate number)",
    systemPromptAddon: `The user wants to preview an estimate. Generate APP_DATA with full estimate: number, client, line items, subtotal, total, validity period, status, terms.`,
  },
  "ghl-order-detail": {
    category: "detail",
    question: "Which order would you like to view? (search by order number, customer, or date)",
    systemPromptAddon: `The user wants to view order details. Generate APP_DATA with: order number, customer, items, quantities, prices, total, shipping status, tracking.`,
  },
  "ghl-product-detail": {
    category: "detail",
    question: "Which product would you like to view? (search by name, SKU, or category)",
    systemPromptAddon: `The user wants to view product details. Generate APP_DATA with: name, description, price, variants, stock, images, category, reviews.`,
  },
  "ghl-course-detail": {
    category: "detail",
    question: "Which course would you like to view? (search by title or category)",
    systemPromptAddon: `The user wants to view course details. Generate APP_DATA with: title, description, modules, lessons, enrollments, completion rate, price, status.`,
  },
  "ghl-funnel-detail": {
    category: "detail",
    question: "Which funnel would you like to view? (search by name or type)",
    systemPromptAddon: `The user wants to view funnel details. Generate APP_DATA with: name, steps, conversion rates per step, traffic, revenue, A/B test status.`,
  },
  "ghl-workflow-detail": {
    category: "detail",
    question: "Which GHL workflow would you like to view? (search by name or trigger type)",
    systemPromptAddon: `The user wants to view workflow details. Generate APP_DATA with: name, trigger, actions, conditions, status, execution history, error logs.`,
  },
  "ghl-user-detail": {
    category: "detail",
    question: "Which team member would you like to view? (search by name or role)",
    systemPromptAddon: `The user wants to view user details. Generate APP_DATA with: name, role, permissions, activity stats, last login, assigned contacts/pipelines.`,
  },
  "ghl-message-detail": {
    category: "detail",
    question: "Which message would you like to view? (search by contact, date, or channel)",
    systemPromptAddon: `The user wants to view message details. Generate APP_DATA with: full message content, sender/recipient, channel, timestamp, delivery status, attachments.`,
  },
  "ghl-call-detail": {
    category: "detail",
    question: "Which call would you like to view? (search by contact, date, or phone number)",
    systemPromptAddon: `The user wants to view call details. Generate APP_DATA with: caller/callee, duration, recording URL, transcript, timestamp, disposition, notes.`,
  },
  "ghl-conversation-thread": {
    category: "detail",
    question: "Which conversation thread would you like to view? (search by contact name or channel)",
    systemPromptAddon: `The user wants to view a conversation thread. Generate APP_DATA with: contact info, full message history, channel type, timestamps, read receipts.`,
  },
  "ghl-email-template-preview": {
    category: "detail",
    question: "Which email template would you like to preview? (search by name or category)",
    systemPromptAddon: `The user wants to preview an email template. Generate APP_DATA with: template name, subject line, HTML preview, variables/merge fields, usage stats.`,
  },
  "twilio-flow-diagram": {
    category: "detail",
    question: "Which Studio flow would you like to view the diagram for? (search by name)",
    systemPromptAddon: `The user wants to view a Studio flow diagram. Generate APP_DATA with: flow name, nodes/widgets, connections, trigger type, and a description of the flow logic.`,
  },
  "twilio-deep-scan-report": {
    category: "detail",
    question: "Which phone number or contact would you like to run a deep scan on?",
    systemPromptAddon: `The user wants a deep scan report. Generate APP_DATA with: number, carrier info, line type, fraud risk score, caller name, location data, and validation status.`,
  },
  "twilio-conversation-thread": {
    category: "detail",
    question: "Which conversation would you like to view? (search by contact or channel)",
    systemPromptAddon: `The user wants to view a Twilio conversation. Generate APP_DATA with: participant info, message history, channel (SMS/WhatsApp/chat), timestamps, media attachments.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // CREATOR CATEGORY — "What would you like to create?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-contact-creator": {
    category: "creator",
    question: "Tell me about the contact you'd like to create — name, email, phone, and any tags or notes?",
    systemPromptAddon: `The user wants to create a new contact. Generate APP_DATA with pre-filled contact form data based on what they provided: { firstName, lastName, email, phone, tags: [], source, notes, companyName? }. Fill in what they gave you, leave other fields empty.`,
  },
  "ghl-invoice-builder": {
    category: "creator",
    question: "Who is this invoice for, and what line items should it include? (client name, services/products, amounts)",
    systemPromptAddon: `The user wants to create an invoice. Generate APP_DATA with: { client: { name, email }, lineItems: [{ description, quantity, rate, amount }], dueDate, notes, taxRate }. Pre-fill from user's description.`,
  },
  "ghl-estimate-builder": {
    category: "creator",
    question: "Who is this estimate for, and what should it include? (client, services/products, pricing)",
    systemPromptAddon: `The user wants to create an estimate. Generate APP_DATA with: { client: { name, email }, lineItems: [{ description, quantity, rate }], validUntil, notes, terms }. Pre-fill from user's description.`,
  },
  "ghl-message-composer": {
    category: "creator",
    question: "Who do you want to message, and what channel? (SMS, email, or chat — and what should the message say?)",
    systemPromptAddon: `The user wants to compose a message. Generate APP_DATA with: { to: { name, channel }, subject?, body, channel: "sms"|"email"|"chat" }. Pre-fill with the user's input.`,
  },
  "ghl-social-post-composer": {
    category: "creator",
    question: "What would you like to post, and on which platforms? (Facebook, Instagram, Google My Business — and when?)",
    systemPromptAddon: `The user wants to compose a social post. Generate APP_DATA with: { content, platforms: string[], scheduledDate?, mediaUrl?, hashtags?: string[] }. Pre-fill from user's description.`,
  },
  "ghl-appointment-booker": {
    category: "creator",
    question: "Who is the appointment for, which calendar, and what date/time works? (contact name, service type, preferred time)",
    systemPromptAddon: `The user wants to book an appointment. Generate APP_DATA with: { contact: { name, email, phone }, calendar, date, time, duration, serviceType, notes }. Pre-fill from user's description.`,
  },
  "meta-ads-audience-builder": {
    category: "creator",
    question: "Describe the audience you want to build — demographics, interests, behaviors, or a lookalike source?",
    systemPromptAddon: `The user wants to build a Meta ad audience. Generate APP_DATA with: { name, type: "custom"|"lookalike"|"saved", demographics: { ageMin, ageMax, genders, locations }, interests: [], behaviors: [], lookalikeSeed? }`,
  },
  "meta-ads-campaign-builder": {
    category: "creator",
    question: "What kind of Meta ad campaign do you want to create? (objective, budget, target audience, and ad format)",
    systemPromptAddon: `The user wants to create a Meta ad campaign. Generate APP_DATA with: { name, objective, dailyBudget, audience, placements, adFormat, schedule }. Pre-fill from user's description.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // CALENDAR CATEGORY — "What date range would you like to see?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-calendar-view": {
    category: "calendar",
    question: "What date range would you like to see, and which calendar? (e.g., this week, February, or a specific calendar)",
    skipLabel: "This week",
    systemPromptAddon: `The user is viewing the Calendar. Generate APP_DATA with: { dateRange: { start, end }, calendarId?, events: [{ title, date, time, duration, contact, status }] }. Filter to requested date range.`,
  },
  "ghl-calendar-resources": {
    category: "calendar",
    question: "Which resources/team members and date range would you like to see availability for?",
    skipLabel: "This week",
    systemPromptAddon: `The user is viewing Calendar Resources. Generate APP_DATA with: { dateRange, resources: [{ name, role, availability: [{ date, slots }] }] }`,
  },
  "ghl-free-slots-finder": {
    category: "calendar",
    question: "Which calendar and date range should I search for free slots? (e.g., next week, a specific team member's calendar)",
    skipLabel: "This week",
    systemPromptAddon: `The user is looking for free appointment slots. Generate APP_DATA with: { calendar, dateRange, freeSlots: [{ date, time, duration }] }`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // SEARCH CATEGORY — "What are you looking for?"
  // ═══════════════════════════════════════════════════════════════════════════

  "n8n-node-config": {
    category: "search",
    question: "Which integration or node are you looking for? (e.g., Slack, Gmail, HTTP Request, or search by category)",
    skipLabel: "Show popular nodes",
    systemPromptAddon: `The user is exploring n8n nodes. Generate APP_DATA with: { query?, results: [{ name, type, category, description, icon }] }. Show relevant nodes based on search.`,
  },
  "n8n-workflow-templates": {
    category: "search",
    question: "What kind of automation template are you looking for? (e.g., lead capture, email marketing, data sync, or by integration)",
    skipLabel: "Show popular templates",
    systemPromptAddon: `The user is searching workflow templates. Generate APP_DATA with: { query?, results: [{ name, description, nodes: string[], category, usageCount }] }`,
  },
  "twilio-number-hunt": {
    category: "search",
    question: "What kind of phone number are you looking for? (area code, city, toll-free, SMS/voice capable, vanity number)",
    skipLabel: "Show available numbers",
    systemPromptAddon: `The user is searching for phone numbers. Generate APP_DATA with: { criteria: { areaCode?, city?, type?, capabilities? }, results: [{ number, type, capabilities, monthlyPrice, location }] }`,
  },
  "meta-ads-ad-library-browser": {
    category: "search",
    question: "What ads are you looking for in the Meta Ad Library? (search by advertiser, keyword, industry, or competitor name)",
    skipLabel: "Show trending ads",
    systemPromptAddon: `The user is browsing the Meta Ad Library. Generate APP_DATA with: { query, results: [{ advertiserName, adText, platform, startDate, status, estimatedSpend, creative }] }`,
  },
  "google-ads-search-terms": {
    category: "search",
    question: "Which campaign or ad group's search terms would you like to analyze? Or search for specific terms?",
    skipLabel: "Show recent search terms",
    systemPromptAddon: `The user is analyzing Google Ads search terms. Generate APP_DATA with: { campaign?, results: [{ searchTerm, matchType, impressions, clicks, CTR, conversions, costPerConversion }] }`,
  },
  "google-ads-keyword-analyzer": {
    category: "search",
    question: "What keywords or topics would you like to analyze? (enter keywords, a URL, or a topic to get ideas)",
    skipLabel: "Show top keywords",
    systemPromptAddon: `The user wants keyword analysis. Generate APP_DATA with: { keywords: [{ keyword, avgMonthlySearches, competition, suggestedBid, trend }], relatedKeywords: [] }`,
  },
  "gsc-quick-wins-board": {
    category: "search",
    question: "What kind of SEO quick wins are you looking for? (e.g., pages close to page 1, high-impression low-CTR, specific topic)",
    skipLabel: "Show all quick wins",
    systemPromptAddon: `The user is looking for SEO quick wins. Generate APP_DATA with: { opportunities: [{ url, query, position, impressions, ctr, estimatedClickGain, recommendation }] }`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // PIPELINE CATEGORY — "Which pipeline would you like to view?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-pipeline-kanban": {
    category: "pipeline",
    question: "Which pipeline would you like to view? (e.g., Sales, Onboarding, Support, or a specific pipeline name)",
    skipLabel: "Show default pipeline",
    systemPromptAddon: `The user is viewing the Pipeline Kanban board. Generate APP_DATA with: { pipeline: { name, id }, stages: [{ name, opportunities: [{ name, value, contact, daysInStage }] }] }. Populate with the requested pipeline.`,
  },
  "ghl-opportunity-editor": {
    category: "pipeline",
    question: "Which opportunity would you like to edit? (search by name, contact, or pipeline)",
    skipLabel: "Show default pipeline",
    systemPromptAddon: `The user wants to edit an opportunity. Generate APP_DATA with: { opportunity: { name, value, stage, contact, pipeline, customFields, notes } }. Pre-populate with the found opportunity.`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // MONITOR CATEGORY — "What would you like to check?"
  // ═══════════════════════════════════════════════════════════════════════════

  "n8n-health-monitor": {
    category: "monitor",
    question: "What would you like to check? (e.g., overall status, failed workflows, execution performance, error rates)",
    skipLabel: "Show overall status",
    systemPromptAddon: `The user is checking n8n health. Generate APP_DATA with: { status: "healthy"|"degraded"|"critical", activeWorkflows, failedExecutions24h, avgExecutionTime, errorRate, alerts: [] }`,
  },
  "twilio-health-check": {
    category: "monitor",
    question: "What would you like to check? (e.g., overall status, message delivery rates, API health, number status)",
    skipLabel: "Show overall status",
    systemPromptAddon: `The user is checking Twilio health. Generate APP_DATA with: { status, messageDeliveryRate, apiLatency, activeNumbers, alerts, recentErrors }`,
  },
  "twilio-deploy-status": {
    category: "monitor",
    question: "Which deployment or service would you like to check? (e.g., functions, Studio flows, or all services)",
    skipLabel: "Show all services",
    systemPromptAddon: `The user is checking Twilio deploy status. Generate APP_DATA with: { services: [{ name, status, lastDeployed, version, environment }] }`,
  },
  "twilio-compliance-check": {
    category: "monitor",
    question: "What compliance area would you like to check? (e.g., A2P 10DLC registration, TrustHub status, messaging policies)",
    skipLabel: "Show overall compliance",
    systemPromptAddon: `The user is checking Twilio compliance. Generate APP_DATA with: { overallScore, brandRegistration: { status }, a2p10dlc: { status }, trustHub: { status }, recommendations: [] }`,
  },
  "gsc-url-health-inspector": {
    category: "monitor",
    question: "Which URLs would you like to inspect? (enter specific URLs, a section of your site, or check all important pages)",
    skipLabel: "Show top pages health",
    systemPromptAddon: `The user is inspecting URL health. Generate APP_DATA with: { urls: [{ url, indexingStatus, lastCrawled, mobileUsability, richResults, issues }] }`,
  },
  "gsc-cannibalization-map": {
    category: "monitor",
    question: "Which keywords or pages would you like to check for cannibalization? (or check the full site)",
    skipLabel: "Show all cannibalization issues",
    systemPromptAddon: `The user is checking keyword cannibalization. Generate APP_DATA with: { issues: [{ keyword, competingPages: [{ url, position, impressions, clicks }], recommendation }] }`,
  },
  "gsc-content-decay-tracker": {
    category: "monitor",
    question: "Which pages or time period would you like to check for content decay? (e.g., last 3 months, specific section)",
    skipLabel: "Show all decaying content",
    systemPromptAddon: `The user is tracking content decay. Generate APP_DATA with: { decayingPages: [{ url, peakTraffic, currentTraffic, declinePercent, severity, recommendation }] }`,
  },
  "twilio-batch-validate": {
    category: "monitor",
    question: "Which phone numbers would you like to validate? (paste numbers, or describe the source — e.g., all contacts, a CSV list)",
    skipLabel: "Show validation status",
    systemPromptAddon: `The user wants to batch validate numbers. Generate APP_DATA with: { total, valid, invalid, results: [{ number, valid, carrier, lineType, error? }] }`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // CONFIG CATEGORY — "What would you like to configure?"
  // ═══════════════════════════════════════════════════════════════════════════

  "ghl-custom-fields-manager": {
    category: "config",
    question: "What would you like to do with custom fields? (view all, add a new field, edit existing, or organize by group)",
    skipLabel: "Show all fields",
    systemPromptAddon: `The user is managing custom fields. Generate APP_DATA with: { fields: [{ name, type, group, options?, required, description }], groups: string[] }`,
  },
  "ghl-team-management": {
    category: "config",
    question: "What would you like to manage? (view team members, update roles, check permissions, or add a new member)",
    skipLabel: "Show all team members",
    systemPromptAddon: `The user is managing their team. Generate APP_DATA with: { members: [{ name, email, role, permissions: string[], status, lastActive }] }`,
  },
  "ghl-social-accounts": {
    category: "config",
    question: "What would you like to do with your social accounts? (view connected, add new, check status, or troubleshoot)",
    skipLabel: "Show connected accounts",
    systemPromptAddon: `The user is managing social accounts. Generate APP_DATA with: { accounts: [{ platform, name, status, followers, lastPost, permissions }] }`,
  },
  "twilio-agent-status": {
    category: "config",
    question: "What would you like to check or configure for agents? (view status, update availability, check assignments)",
    skipLabel: "Show all agents",
    systemPromptAddon: `The user is managing agent status. Generate APP_DATA with: { agents: [{ name, status: "available"|"busy"|"offline", currentTask?, activeCalls, avgHandleTime }] }`,
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // RESEARCH CATEGORY — "What would you like to research?"
  // ═══════════════════════════════════════════════════════════════════════════

  "competitor-intake-form": {
    category: "research",
    question: "Tell me about your business and competitors — company name, website, industry, and which competitors you want to analyze?",
    systemPromptAddon: `The user wants to start competitor research. Generate APP_DATA to pre-fill the intake form: { company: { name, url, industry, description }, competitors: [{ name, url, notes }], focusAreas: string[] }`,
  },
  "competitor-dashboard": {
    category: "research",
    question: "Which competitors would you like to see the analysis for? (list competitor names or show all)",
    systemPromptAddon: `The user wants to view competitor research results. Generate APP_DATA with: { competitors: [{ name, url, strengths: [], weaknesses: [], pricing, features }], insights: [] }`,
  },
  "google-ads-budget-optimizer": {
    category: "research",
    question: "What's your current budget and goal? (e.g., $5K/month targeting max conversions, or redistribute across campaigns)",
    systemPromptAddon: `The user wants budget optimization. Generate APP_DATA with: { currentBudget, campaigns: [{ name, currentSpend, suggestedSpend, expectedImpact }], totalSavings, projectedImprovement }`,
  },
  "google-ads-recommendations": {
    category: "research",
    question: "What area would you like recommendations for? (e.g., keywords, bids, ad copy, extensions, or show all)",
    systemPromptAddon: `The user wants Google Ads recommendations. Generate APP_DATA with: { recommendations: [{ type, impact, description, action, estimatedChange }], overallScore }`,
  },
  "ghl-duplicate-checker": {
    category: "research",
    question: "What would you like to check for duplicates? (contacts, companies, or both — and how strict should matching be?)",
    systemPromptAddon: `The user wants to find duplicates. Generate APP_DATA with: { duplicateGroups: [{ contacts: [{ name, email, phone }], confidence, suggestedAction }], totalDuplicates }`,
  },
};

// ─── Export ──────────────────────────────────────────────────────────────────

export function getAppIntake(appId: string): AppIntake | null {
  // Check for explicit intake config
  if (APP_INTAKES[appId]) {
    return APP_INTAKES[appId];
  }

  // Apps not in the list get a generic intake question
  return {
    category: "general",
    question: "What would you like to see? Describe what you're looking for.",
    skipLabel: "Show default view",
    systemPromptAddon: "Generate appropriate APP_DATA for this app based on the user's request.",
  };
}
