/**
 * AI Avatar — Suggested Actions & Follow-Up Prompts
 * ---------------------------------------------------
 * Generates structured actions the user can click, and follow-up
 * prompts to keep the conversation going.
 *
 * Action types:
 *   navigate      — go to a specific page in the app
 *   create_task   — create a task in the Execution Hub
 *   generate_report — trigger a report summary
 *   run_audit     — start a technical or performance audit
 *   create_brief  — start a new content brief
 *   export        — export data (CSV, PDF, etc.)
 *
 * Each action is a simple object the frontend renders as a button.
 * The frontend handles the actual execution (navigation, API call, etc.)
 */

// ─── Types ───────────────────────────────────────────────────────────────────

export type ActionType =
  | "navigate"
  | "create_task"
  | "generate_report"
  | "run_audit"
  | "create_brief"
  | "export";

export interface SuggestedAction {
  /** What type of action this is — the frontend uses this to decide what to do */
  type: ActionType;
  /** Button label shown to the user */
  label: string;
  /** For "navigate" actions: the page to go to */
  href?: string;
  /** Extra data the frontend might need (e.g. task title, report type) */
  payload?: Record<string, string>;
}

export interface SuggestedFollowUp {
  /** The prompt text the user can click to send */
  prompt: string;
}

export interface ActionResult {
  actions: SuggestedAction[];
  followUps: SuggestedFollowUp[];
}

// ─── Generator ───────────────────────────────────────────────────────────────

/**
 * Given the user's message and the detected module, generate relevant
 * suggested actions and follow-up prompts.
 */
export function generateActions(
  message: string,
  module: string,
  currentPage: string
): ActionResult {
  const q = message.toLowerCase();

  // ── Traffic / Dashboard ──
  if (q.includes("traffic") || q.includes("sessions") || q.includes("visit") || module === "Dashboard") {
    return {
      actions: [
        { type: "navigate", label: "Open Dashboard", href: "/dashboard" },
        { type: "generate_report", label: "Generate Traffic Report", payload: { reportType: "traffic" } },
        { type: "create_task", label: "Create Task: Monitor Traffic", payload: { title: "Set up weekly traffic monitoring alert", priority: "medium", category: "seo" } },
        { type: "navigate", label: "View AI Visibility", href: "/ai-visibility" },
      ],
      followUps: [
        { prompt: "Which pages are losing the most traffic?" },
        { prompt: "How does my AI search traffic compare to organic?" },
        { prompt: "What should I do to increase traffic this month?" },
      ],
    };
  }

  // ── Conversions / Revenue ──
  if (q.includes("conversion") || q.includes("revenue") || q.includes("roi") || module === "Conversion Intelligence") {
    return {
      actions: [
        { type: "navigate", label: "Open Site Tag Analytics", href: "/site-tag-analytics" },
        { type: "generate_report", label: "Generate Conversion Report", payload: { reportType: "conversions" } },
        { type: "create_task", label: "Create Task: Optimize Phone CTA", payload: { title: "Add click-to-call CTA to top 5 mobile landing pages", priority: "high", category: "seo" } },
        { type: "create_brief", label: "Create LLMO Brief for High-Intent Queries", payload: { type: "llmo", topic: "high-intent conversion queries" } },
      ],
      followUps: [
        { prompt: "Which channel has the best cost per conversion?" },
        { prompt: "Show me the conversion funnel breakdown" },
        { prompt: "What landing pages convert best?" },
      ],
    };
  }

  // ── Technical Audit ──
  if (q.includes("technical") || q.includes("audit") || q.includes("error") || q.includes("fix") || q.includes("broken") || module === "Technical Audit") {
    return {
      actions: [
        { type: "navigate", label: "Open Technical Audit", href: "/technical-audit" },
        { type: "create_task", label: "Create Task: Fix Meta Descriptions", payload: { title: "Write meta descriptions for 14 pages", priority: "high", category: "seo" } },
        { type: "create_task", label: "Create Task: Fix Broken Links", payload: { title: "Fix 17 broken internal links", priority: "high", category: "technical" } },
        { type: "run_audit", label: "Run Fresh Audit", payload: { auditType: "technical" } },
      ],
      followUps: [
        { prompt: "Which errors are hurting my rankings the most?" },
        { prompt: "How long will it take to fix all critical issues?" },
        { prompt: "Show me the quick wins I can fix today" },
      ],
    };
  }

  // ── Competitors ──
  if (q.includes("competitor") || q.includes("compete") || q.includes("moz") || q.includes("semrush") || module === "Competitors") {
    return {
      actions: [
        { type: "navigate", label: "Open Competitors", href: "/competitors" },
        { type: "generate_report", label: "Generate Competitor Report", payload: { reportType: "competitors" } },
        { type: "create_brief", label: "Create Brief: AI Visibility Content", payload: { type: "llmo", topic: "AI visibility — no competitor covers this" } },
        { type: "create_task", label: "Create Task: Target Aging Content", payload: { title: "Write fresh alternatives for 12 aging competitor pages", priority: "medium", category: "content" } },
      ],
      followUps: [
        { prompt: "What content gaps can I exploit against Moz?" },
        { prompt: "Which competitor is growing fastest?" },
        { prompt: "How can I outrank SEMrush on my target keywords?" },
      ],
    };
  }

  // ── Local GEO ──
  if (q.includes("local") || q.includes("geo") || q.includes("city") || q.includes("market") || module === "Local GEO") {
    return {
      actions: [
        { type: "navigate", label: "Open Local GEO", href: "/local-geo" },
        { type: "create_task", label: "Create Task: Denver Landing Page", payload: { title: "Create Denver location page to enter untapped market", priority: "high", category: "content" } },
        { type: "create_task", label: "Create Task: Fix Phoenix Decline", payload: { title: "Audit Phoenix pages for thin content and cannibalization", priority: "high", category: "seo" } },
        { type: "generate_report", label: "Generate Local Performance Report", payload: { reportType: "local-geo" } },
      ],
      followUps: [
        { prompt: "Why is Phoenix declining?" },
        { prompt: "How do I enter the Denver market?" },
        { prompt: "What's driving Seattle's strong performance?" },
      ],
    };
  }

  // ── SEO Content Brief ──
  if (q.includes("seo brief") || q.includes("seo content") || q.includes("keyword") || q.includes("serp") || module === "SEO Content Brief") {
    return {
      actions: [
        { type: "navigate", label: "Open SEO Briefs", href: "/content-brief" },
        { type: "create_brief", label: "Create New SEO Brief", payload: { type: "seo", topic: "" } },
        { type: "create_task", label: "Create Task: Improve Internal Links", payload: { title: "Add 3-5 internal links to each active brief", priority: "medium", category: "content" } },
        { type: "export", label: "Export Brief Data", payload: { format: "csv" } },
      ],
      followUps: [
        { prompt: "Which keywords should I target next?" },
        { prompt: "How can I improve my content scores?" },
        { prompt: "What topics are competitors ranking for that I'm not?" },
      ],
    };
  }

  // ── LLMO Content Brief ──
  if (q.includes("llmo") || q.includes("ai content") || q.includes("ai brief") || q.includes("answer-ready") || module === "LLMO Content Brief") {
    return {
      actions: [
        { type: "navigate", label: "Open LLMO Briefs", href: "/llmo-content-brief" },
        { type: "create_brief", label: "Create New LLMO Brief", payload: { type: "llmo", topic: "" } },
        { type: "create_task", label: "Create Task: Retrofit 5 Pages", payload: { title: "Add FAQ blocks and answer-ready formatting to 5 existing pages", priority: "high", category: "content" } },
        { type: "navigate", label: "View AI Visibility", href: "/ai-visibility" },
      ],
      followUps: [
        { prompt: "Which pages should I retrofit for AI search?" },
        { prompt: "What's the difference between SEO and LLMO optimization?" },
        { prompt: "How do I get cited by ChatGPT?" },
      ],
    };
  }

  // ── Execution Hub / Tasks ──
  if (q.includes("task") || q.includes("overdue") || q.includes("execution") || q.includes("todo") || module === "Execution Hub") {
    return {
      actions: [
        { type: "navigate", label: "Open Execution Hub", href: "/execution-hub" },
        { type: "create_task", label: "Create New Task", payload: { title: "", priority: "medium", category: "seo" } },
        { type: "generate_report", label: "Generate Task Progress Report", payload: { reportType: "tasks" } },
        { type: "export", label: "Export Task List", payload: { format: "csv" } },
      ],
      followUps: [
        { prompt: "What are my most overdue tasks?" },
        { prompt: "Which tasks will have the biggest impact?" },
        { prompt: "How many tasks did we complete this week?" },
      ],
    };
  }

  // ── Page Launch Tracker ──
  if (q.includes("launch") || q.includes("pipeline") || q.includes("go live") || module === "Page Launch Tracker") {
    return {
      actions: [
        { type: "navigate", label: "Open Launch Tracker", href: "/page-launch-tracker" },
        { type: "create_task", label: "Create Task: Clear Review Queue", payload: { title: "Review and approve 3 pages waiting in review queue", priority: "high", category: "content" } },
        { type: "generate_report", label: "Generate Launch Pipeline Report", payload: { reportType: "launches" } },
        { type: "navigate", label: "Open Page Studio", href: "/page-studio" },
      ],
      followUps: [
        { prompt: "Which pages are ready to launch right now?" },
        { prompt: "What's slowing down my launch pipeline?" },
        { prompt: "How is my top-performing launched page doing?" },
      ],
    };
  }

  // ── Priorities / general help ──
  if (q.includes("what should") || q.includes("priority") || q.includes("help") || q.includes("focus") || q.includes("next step")) {
    return {
      actions: [
        { type: "create_task", label: "Create Task: Fix Meta Descriptions", payload: { title: "Write meta descriptions for 14 pages", priority: "high", category: "seo" } },
        { type: "create_task", label: "Create Task: Fix Broken Links", payload: { title: "Fix 17 broken internal links", priority: "high", category: "technical" } },
        { type: "navigate", label: "Open Execution Hub", href: "/execution-hub" },
        { type: "generate_report", label: "Generate Executive Summary", payload: { reportType: "executive" } },
      ],
      followUps: [
        { prompt: "Break down my priorities by this week vs this month" },
        { prompt: "What's the fastest way to increase traffic?" },
        { prompt: "Show me my quick wins across all modules" },
      ],
    };
  }

  // ── Default: context-aware based on current page ──
  return {
    actions: [
      ...(currentPage !== "/dashboard" ? [{ type: "navigate" as ActionType, label: "Go to Dashboard", href: "/dashboard" }] : []),
      { type: "generate_report", label: "Generate Summary Report", payload: { reportType: "executive" } },
      { type: "create_task", label: "Create a Task", payload: { title: "", priority: "medium", category: "seo" } },
      { type: "navigate", label: "View Recommendations", href: "/recommendations" },
    ],
    followUps: [
      { prompt: "What should I focus on this week?" },
      { prompt: "Give me a summary of my biggest issues" },
      { prompt: "Which module needs the most attention?" },
    ],
  };
}
