import { OPPORTUNITY_TYPE_LABELS } from "@/lib/constants";
import { calculateBrandScore } from "@/lib/brand-score";
import type {
  BrandScore,
  BusinessProfile,
  Competitor,
  OnboardingInput,
  Opportunity,
  OpportunityType,
  Recommendation,
} from "@/lib/types";

const ALL_TYPES: OpportunityType[] = [
  "buyer",
  "competitor_weakness",
  "market_gap",
  "content",
  "partnership",
  "reputation",
  "geographic",
  "pricing",
  "product",
  "government_contract",
];

function valueFromRange(range: string, multiplier: number) {
  const base: Record<string, number> = {
    "Pre-revenue": 2500,
    "Under $5K/mo": 5000,
    "$5K–$20K/mo": 12000,
    "$20K–$50K/mo": 28000,
    "$50K–$100K/mo": 45000,
    "$100K+/mo": 75000,
  };
  return Math.round((base[range] ?? 8000) * multiplier);
}

export function generateMockOpportunities(
  input: OnboardingInput,
  profile: BusinessProfile
): Opportunity[] {
  return ALL_TYPES.map((type, i) => ({
    id: `opp-${i + 1}`,
    title: `${OPPORTUNITY_TYPE_LABELS[type]} for ${input.businessName}`,
    type,
    description: buildDescription(type, input, profile),
    source: buildSource(type),
    estimatedValue: valueFromRange(input.monthlyRevenueRange, 0.15 + i * 0.04),
    confidenceScore: clampScore(62 + i * 3),
    urgencyScore: clampScore(55 + (i % 3) * 12),
    recommendedAction: buildAction(type, input),
    aiOutreach: buildOutreach(type, input),
    status: i < 2 ? "new" : i < 4 ? "saved" : "new",
  }));
}

function buildDescription(type: OpportunityType, input: OnboardingInput, profile: BusinessProfile) {
  const map: Record<OpportunityType, string> = {
    buyer: `A ${input.targetCustomer.toLowerCase()} is actively looking for ${input.productsServices.toLowerCase()} in ${input.location}.`,
    competitor_weakness: profile.suggestedCompetitors[0]
      ? `${profile.suggestedCompetitors[0]} has service gaps you can exploit with faster response and clearer offers.`
      : "A competitor in your market has weak reviews around response time.",
    market_gap: `Buyers in ${input.industry} want ${input.productsServices.toLowerCase()} but struggle to find trusted providers.`,
    content: `Create authority content around "${input.biggestChallenge}" to attract inbound demand.`,
    partnership: `Partner with a complementary local business serving ${input.targetCustomer.toLowerCase()}.`,
    reputation: "Recent review trends suggest an opportunity to win trust with proactive responses.",
    geographic: `Expand outreach in nearby areas around ${input.location} where demand is underserved.`,
    pricing: "Package your core offer into a tier that reduces buyer hesitation.",
    product: `Promote your highest-margin service: ${input.productsServices.split(",")[0] ?? input.productsServices}.`,
    government_contract: `Federal solicitations in ${input.industry} may match your capabilities — search SAM.gov for NAICS-aligned contracts near ${input.location}.`,
  };
  return map[type];
}

function buildSource(type: OpportunityType) {
  const sources: Record<OpportunityType, string> = {
    buyer: "Mock: Reddit / local forum intent",
    competitor_weakness: "Mock: Google Reviews analysis",
    market_gap: "Mock: Market scan",
    content: "Mock: Search trend signal",
    partnership: "Mock: Local business network",
    reputation: "Mock: Review monitoring",
    geographic: "Mock: Geographic demand map",
    pricing: "Mock: Competitive pricing scan",
    product: "Mock: Offer performance model",
    government_contract: "Mock: SAM.gov contract search",
  };
  return sources[type];
}

function buildAction(type: OpportunityType, input: OnboardingInput) {
  const actions: Record<OpportunityType, string> = {
    buyer: "Send personalized outreach within 24 hours",
    competitor_weakness: "Launch comparison landing page this week",
    market_gap: "Publish a category guide and capture leads",
    content: "Ship 2 posts answering top buyer questions",
    partnership: "Email 3 potential partners with a co-marketing pitch",
    reputation: "Respond to all pending reviews and request 5 new ones",
    geographic: "Run geo-targeted ads in adjacent zip codes",
    pricing: "Test a starter package with clear ROI framing",
    product: "Feature top service in email + social for 7 days",
    government_contract: "Import live federal contracts from SAM.gov and prepare a capability statement",
  };
  return actions[type];
}

function buildOutreach(type: OpportunityType, input: OnboardingInput) {
  if (type === "buyer" || type === "partnership") {
    return `Hi — I noticed you're looking for help with ${input.productsServices.toLowerCase()}. We specialize in exactly that at ${input.businessName}. Open to a quick 15-min call?`;
  }
  if (type === "content") {
    return `Post idea: "3 signs ${input.targetCustomer.toLowerCase()} needs ${input.productsServices.toLowerCase()} — and what to do next."`;
  }
  return `Suggested message/ad concept for ${OPPORTUNITY_TYPE_LABELS[type]} at ${input.businessName}.`;
}

export function generateMockCompetitors(profile: BusinessProfile): Competitor[] {
  return profile.suggestedCompetitors.slice(0, 3).map((name, i) => ({
    id: `comp-${i + 1}`,
    name,
    website: `https://${name.toLowerCase().replace(/\s+/g, "")}.example`,
    strengths: ["Established brand", "Local visibility", "Category familiarity"].slice(0, 2 + (i % 2)),
    weaknesses: ["Generic messaging", "Slow follow-up", "Limited social proof"].slice(0, 2 + (i % 2)),
    positioning: `Positioned as a mainstream ${profile.productsServices.split(",")[0] ?? "service"} provider`,
    pricingNotes: i === 0 ? "Premium pricing, longer sales cycle" : "Budget positioning, low differentiation",
    customerComplaints: ["Slow response times", "Unclear pricing", "Inconsistent quality"].slice(0, 2),
    beatOpportunity: `Win on speed, clarity, and outcome-focused messaging for ${profile.targetAudience.toLowerCase()}.`,
  }));
}

export function generateMockRecommendations(
  input: OnboardingInput,
  opportunities: Opportunity[]
): Recommendation[] {
  const top = opportunities.sort((a, b) => b.estimatedValue - a.estimatedValue)[0];
  return [
    {
      id: "rec-1",
      title: "Execute today's highest-value opportunity",
      whyItMatters: top
        ? `${top.title} has $${top.estimatedValue.toLocaleString()} estimated value with ${top.confidenceScore}% confidence.`
        : "Focus beats scattered effort when bandwidth is limited.",
      whatToDoNext: top?.recommendedAction ?? "Pick one opportunity and ship it today.",
      revenuePotential: top?.estimatedValue ?? 5000,
      priority: "high",
      socialPost: `We help ${input.targetCustomer.toLowerCase()} with ${input.productsServices.toLowerCase()}. DM us if ${input.biggestChallenge.toLowerCase()} is holding you back.`,
      emailDraft: `Subject: Quick idea for ${input.businessName}\n\nHi {{name}}, based on what we see in ${input.industry}, there's a clear way to ${input.revenueGoal.toLowerCase()}. Can we share a 10-minute plan?`,
      dmMessage: `Hey {{name}} — saw you might need help with ${input.productsServices.toLowerCase()}. We specialize in this at ${input.businessName}. Worth a quick chat?`,
      adConcept: `Headline: Stop losing deals to ${input.biggestChallenge.toLowerCase()}. Sub: ${input.businessName} helps ${input.targetCustomer.toLowerCase()} win.`,
      offerIdea: `Launch a 14-day "${input.productsServices.split(",")[0] ?? "Core Offer"} Sprint" package.`,
      landingHeadline: `${input.businessName}: The ${input.industry} partner built for ${input.targetCustomer.toLowerCase()}`,
    },
    {
      id: "rec-2",
      title: "Fix the brand trust gap",
      whyItMatters: "Trust drives conversion more than traffic in early growth stages.",
      whatToDoNext: "Add 3 proof points and respond to every review this week.",
      revenuePotential: Math.round((top?.estimatedValue ?? 8000) * 0.4),
      priority: "medium",
      socialPost: "Another happy customer. Here's what changed for them → [story]",
      emailDraft: "Follow-up email requesting a review or referral from recent customers.",
    },
    {
      id: "rec-3",
      title: "Run a competitor displacement play",
      whyItMatters: "Competitor weakness opportunities convert when you move fast.",
      whatToDoNext: "Publish a comparison page and share it in outbound.",
      revenuePotential: Math.round((top?.estimatedValue ?? 8000) * 0.55),
      priority: "medium",
    },
  ];
}

export function generateMockBrandScore(input: OnboardingInput): BrandScore {
  return calculateBrandScore(input);
}

export function generateAiSummary(input: OnboardingInput, opportunities: Opportunity[]): string {
  const top = opportunities.sort((a, b) => b.estimatedValue - a.estimatedValue)[0];
  return `Your AI co-founder sees the biggest near-term upside in ${top?.type.replace("_", " ") ?? "buyer demand"}. With ${input.monthlyRevenueRange} current revenue and a goal of ${input.revenueGoal.toLowerCase()}, focus this week on ${top?.recommendedAction.toLowerCase() ?? "one high-confidence play"}. Estimated revenue potential across active opportunities: $${opportunities.reduce((s, o) => s + o.estimatedValue, 0).toLocaleString()}.`;
}

function clampScore(n: number) {
  return Math.max(0, Math.min(100, Math.round(n)));
}
