import type { BrandScore, OnboardingInput } from "@/lib/types";

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

function rangeScore(range: string) {
  const map: Record<string, number> = {
    "Pre-revenue": 20,
    "Under $5K/mo": 35,
    "$5K–$20K/mo": 50,
    "$20K–$50K/mo": 65,
    "$50K–$100K/mo": 78,
    "$100K+/mo": 88,
  };
  return map[range] ?? 45;
}

export function calculateBrandScore(input: OnboardingInput): BrandScore {
  const hasWebsite = Boolean(input.websiteUrl?.trim());
  const visibility = clamp(30 + (hasWebsite ? 25 : 0) + input.industry.length / 3);
  const trust = clamp(35 + (input.productsServices.length > 20 ? 20 : 10) + (hasWebsite ? 15 : 0));
  const demand = clamp(40 + rangeScore(input.monthlyRevenueRange) * 0.35);
  const conversion = clamp(35 + input.targetCustomer.length / 4 + (hasWebsite ? 12 : 0));
  const advocacy = clamp(38 + (input.mainCompetitors ? 8 : 4));

  const overall = clamp(
    visibility * 0.2 + trust * 0.2 + demand * 0.2 + conversion * 0.2 + advocacy * 0.2
  );

  const growthScore = clamp(overall + (input.revenueGoal.length > 10 ? 8 : 0));
  const marketOpportunityScore = clamp(55 + input.productsServices.split(",").length * 6);
  const competitiveRiskScore = clamp(
    input.mainCompetitors ? 55 + input.mainCompetitors.split(",").length * 8 : 38
  );

  return {
    overall,
    visibility,
    trust,
    demand,
    conversion,
    advocacy,
    growthScore,
    marketOpportunityScore,
    competitiveRiskScore,
    suggestions: {
      visibility: hasWebsite
        ? "Increase local SEO and review velocity to expand discovery."
        : "Launch a conversion-focused website to unlock visibility.",
      trust: "Publish proof points, case studies, and transparent pricing.",
      demand: "Run a focused offer campaign tied to your highest-intent audience.",
      conversion: "Tighten your homepage headline and add one clear CTA path.",
      advocacy: "Ask happy customers for reviews and referral introductions.",
    },
  };
}
