import { inferDigitalPresenceFromBusiness } from "@/lib/demo-digital-presence";
import type {
  Business,
  Competitor,
  CompetitorPickShare,
  SocialDimensionScore,
  SocialMediaAnalysis,
  SocialMediaDimension,
  SocialMediaRecommendation,
  SocialPlatform,
  SocialPlatformInsight,
  SocialProfile,
  TrustChannelAnalysis,
} from "@/lib/types";

const DIMENSION_LABELS: Record<SocialMediaDimension, string> = {
  reach: "Reach & audience size",
  consistency: "Posting consistency",
  engagement: "Engagement quality",
  socialProof: "Reviews & social proof",
  competitiveShare: "Share of local picks",
  trustSignal: "Trust on social",
};

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

function parseFollowerCount(raw?: string): number {
  if (!raw) return 0;
  const reviewMatch = raw.match(/(\d+)\s*reviews?/i);
  if (reviewMatch) return parseInt(reviewMatch[1], 10) * 15;
  const starMatch = raw.match(/([\d.]+)★/);
  if (starMatch && !raw.match(/\d+\s*reviews?/i)) {
    return parseFloat(starMatch[1]) * 500;
  }
  const cleaned = raw.replace(/,/g, "").trim().toUpperCase();
  const num = parseFloat(cleaned.replace(/[^0-9.]/g, ""));
  if (Number.isNaN(num)) return 0;
  if (cleaned.includes("M")) return num * 1_000_000;
  if (cleaned.includes("K")) return num * 1_000;
  return num;
}

function totalSocialReach(profiles: SocialProfile[]): number {
  return profiles.reduce((sum, p) => sum + parseFollowerCount(p.followers), 0);
}

function competitorSocialWeight(c: Competitor): number {
  const text = [
    c.name,
    c.positioning ?? "",
    ...c.strengths,
    ...c.weaknesses,
    ...c.customerComplaints,
  ]
    .join(" ")
    .toLowerCase();

  let weight = 40;
  if (text.includes("instagram") || text.includes("social")) weight += 25;
  if (text.includes("review") || text.includes("google")) weight += 20;
  if (text.includes("seo") || text.includes("ads")) weight += 15;
  if (text.includes("national") || text.includes("largest") || text.includes("corporate")) weight += 20;
  if (text.includes("dated") || text.includes("4.1") || text.includes("4.2") || text.includes("4.3")) weight -= 10;
  if (c.customerComplaints.length >= 10) weight -= 15;
  if (c.weaknesses.some((w) => w.toLowerCase().includes("weak"))) weight -= 8;
  return clamp(weight + c.strengths.length * 4);
}

function buildPickShare(business: Business, yourReach: number): CompetitorPickShare[] {
  const competitors = business.competitors.slice(0, 4);
  const yourBase =
    business.brandScore.visibility * 0.35 +
    business.brandScore.trust * 0.35 +
    business.brandScore.advocacy * 0.2 +
    Math.min(yourReach / 200, 40) * 0.1;

  const entries: { name: string; weight: number; reason: string; isYou?: boolean }[] = [
    {
      name: business.input.businessName,
      weight: yourBase,
      reason: `${business.brandScore.trust}/100 trust · ${business.digitalPresence?.socialProfiles.length ?? 0} active channels`,
      isYou: true,
    },
    ...competitors.map((c) => ({
      name: c.name,
      weight: competitorSocialWeight(c),
      reason: c.beatOpportunity.split("—")[0]?.trim() || c.strengths[0] || "Strong local presence",
    })),
  ];

  const total = entries.reduce((s, e) => s + e.weight, 0) || 1;
  return entries
    .map((e) => ({
      name: e.name,
      pickSharePercent: clamp((e.weight / total) * 100),
      reason: e.reason,
      isYou: e.isYou,
    }))
    .sort((a, b) => b.pickSharePercent - a.pickSharePercent);
}

function analyzeTrustChannels(business: Business, profiles: SocialProfile[]): TrustChannelAnalysis {
  const websiteAesthetic = business.websiteAestheticAnalysis?.overallScore;
  const websiteTrustScore = clamp(
    business.brandScore.trust * 0.45 +
      business.brandScore.conversion * 0.25 +
      (websiteAesthetic ?? business.brandScore.trust) * 0.3,
  );

  const googleProfile = profiles.find((p) => p.platform === "google");
  const reviewProof = googleProfile?.followers ?? "";
  const socialTrustScore = clamp(
    business.brandScore.advocacy * 0.35 +
      business.brandScore.visibility * 0.25 +
      Math.min(profiles.length * 12, 36) +
      (reviewProof.includes("★") ? 15 : 0) +
      (parseFollowerCount(reviewProof) > 500 ? 10 : 0),
  );

  const diff = websiteTrustScore - socialTrustScore;
  const strongerChannel: TrustChannelAnalysis["strongerChannel"] =
    Math.abs(diff) <= 5 ? "balanced" : diff > 0 ? "website" : "social";

  const websiteTrustNotes = [
    business.input.websiteUrl
      ? `Website at ${business.input.websiteUrl.replace(/^https?:\/\//, "")} carries brand positioning and conversion proof.`
      : "No website URL on file — trust relies heavily on social and referrals.",
    business.websiteAestheticAnalysis
      ? `Aesthetic score ${business.websiteAestheticAnalysis.overallScore}/100 vs industry ${business.websiteAestheticAnalysis.industryBenchmarkScore}.`
      : `Brand trust score ${business.brandScore.trust}/100 — run website analysis for deeper trust audit.`,
    business.profile.strengths[0] ? `Strength to amplify on-site: ${business.profile.strengths[0]}` : "",
  ].filter(Boolean);

  const socialTrustNotes = [
    profiles.length
      ? `${profiles.length} social profile${profiles.length === 1 ? "" : "s"} active — buyers discover you on ${profiles.map((p) => p.platform).join(", ")}.`
      : "No social profiles linked — competitors may win discovery before trust is built.",
    googleProfile
      ? `Google presence: ${googleProfile.followers ?? "listed"} — critical for local trust.`
      : "Add or optimize Google Business — highest trust impact for local/service brands.",
    business.competitors[0]
      ? `Vs ${business.competitors[0].name}: ${business.competitors[0].beatOpportunity.slice(0, 90)}…`
      : "",
  ].filter(Boolean);

  const verdict =
    strongerChannel === "website"
      ? `Your website creates more trust (${websiteTrustScore}/100) than social (${socialTrustScore}/100). Invest in social proof that mirrors what's working on-site — reviews, guarantees, and real project photos.`
      : strongerChannel === "social"
        ? `Social creates more trust (${socialTrustScore}/100) than your website (${websiteTrustScore}/100). Align homepage and landing pages with the authenticity buyers already feel on social.`
        : `Website (${websiteTrustScore}/100) and social (${socialTrustScore}/100) trust are balanced — keep messaging consistent across both so neither channel contradicts the other.`;

  return {
    websiteTrustScore,
    socialTrustScore,
    strongerChannel,
    websiteTrustNotes,
    socialTrustNotes,
    verdict,
  };
}

function platformInsight(profile: SocialProfile): SocialPlatformInsight {
  const reach = parseFollowerCount(profile.followers);
  const isGoogle = profile.platform === "google";
  const visibilityScore = clamp(
    (isGoogle ? 70 : 45) + Math.min(reach / 300, 30) + (profile.followers?.includes("★") ? 10 : 0),
  );
  const trustContribution = clamp(
    (isGoogle ? 85 : 50) + (profile.followers?.match(/\d+\s*reviews?/i) ? 10 : 0) + Math.min(reach / 500, 10),
  );

  const notes: Record<SocialPlatform, string> = {
    instagram: "Visual proof and before/after content drive discovery for your category.",
    facebook: "Local community trust and paid retargeting hub.",
    linkedin: "B2B credibility and founder-led authority.",
    tiktok: "Short-form discovery — high upside for younger buyers.",
    youtube: "Long-form trust — tutorials and testimonials compound.",
    google: "Highest-intent trust channel — reviews directly influence who gets picked.",
    x: "Real-time brand voice and industry commentary.",
  };

  return {
    platform: profile.platform,
    handle: profile.handle,
    followers: profile.followers,
    visibilityScore,
    trustContribution,
    note: notes[profile.platform],
  };
}

function buildDimensions(
  business: Business,
  yourReach: number,
  pickShare: CompetitorPickShare[],
  trust: TrustChannelAnalysis,
): SocialDimensionScore[] {
  const profiles = business.digitalPresence?.socialProfiles ?? inferDigitalPresenceFromBusiness(business)?.socialProfiles ?? [];
  const yourPick = pickShare.find((p) => p.isYou)?.pickSharePercent ?? 30;
  const benchmark = 72;

  const dims: Array<{ dimension: SocialMediaDimension; yourScore: number; insight: string }> = [
    {
      dimension: "reach",
      yourScore: clamp(business.brandScore.visibility * 0.4 + Math.min(yourReach / 250, 45)),
      insight:
        yourReach > 5000
          ? `Combined reach ~${Math.round(yourReach).toLocaleString()} across ${profiles.length} channels.`
          : "Reach is below category leaders — expand or activate dormant profiles.",
    },
    {
      dimension: "consistency",
      yourScore: clamp(50 + profiles.length * 10 + (business.brandScore.advocacy > 70 ? 15 : 0)),
      insight:
        profiles.length >= 3
          ? "Multi-platform presence — maintain consistent bio, logo, and offer messaging."
          : "Limited platform coverage — buyers may not find you where they search.",
    },
    {
      dimension: "engagement",
      yourScore: clamp(business.brandScore.advocacy * 0.6 + business.brandScore.demand * 0.4),
      insight: "Engagement proxy from advocacy and demand scores — post content that invites replies and shares.",
    },
    {
      dimension: "socialProof",
      yourScore: clamp(business.brandScore.trust * 0.5 + trust.socialTrustScore * 0.5),
      insight: profiles.some((p) => p.platform === "google")
        ? "Google reviews listed — keep review velocity above competitors."
        : "Missing Google Business social proof — biggest trust gap vs local competitors.",
    },
    {
      dimension: "competitiveShare",
      yourScore: yourPick,
      insight: `You win ~${yourPick}% of simulated buyer picks vs ${business.competitors.length} tracked competitors.`,
    },
    {
      dimension: "trustSignal",
      yourScore: trust.socialTrustScore,
      insight: `Social trust ${trust.socialTrustScore}/100 vs website ${trust.websiteTrustScore}/100 — ${trust.strongerChannel === "balanced" ? "channels aligned" : `${trust.strongerChannel} leads`}.`,
    },
  ];

  return dims.map((d) => ({
    dimension: d.dimension,
    label: DIMENSION_LABELS[d.dimension],
    yourScore: d.yourScore,
    industryTopAvg: benchmark,
    gap: benchmark - d.yourScore,
    insight: d.insight,
  }));
}

function buildRecommendations(
  trust: TrustChannelAnalysis,
  dimensions: SocialDimensionScore[],
): SocialMediaRecommendation[] {
  const recs: SocialMediaRecommendation[] = [];
  const sorted = [...dimensions].sort((a, b) => b.gap - a.gap);

  sorted.slice(0, 2).forEach((dim, i) => {
    const actions: Record<SocialMediaDimension, string> = {
      reach: "Boost reach with 3 posts/week on your top platform and cross-link from website footer.",
      consistency: "Sync bios, logo, and CTA across all profiles — one booking link everywhere.",
      engagement: "Add weekly Q&A or poll content tied to your top opportunity.",
      socialProof: "Request 5 new Google reviews this week; repost best reviews to Instagram/Facebook.",
      competitiveShare: "Run comparison content highlighting your beat opportunity vs top competitor.",
      trustSignal: "Film 60-second founder/team intro video for homepage and Instagram Reels.",
    };
    recs.push({
      id: `sm-${dim.dimension}`,
      priority: i === 0 ? "high" : "medium",
      title: `Improve ${dim.label.toLowerCase()}`,
      action: actions[dim.dimension],
      expectedImpact: `Close ${dim.gap}pt gap vs industry top performers`,
    });
  });

  if (trust.strongerChannel === "social") {
    recs.push({
      id: "sm-trust-website",
      priority: "high",
      title: "Bring website trust up to social level",
      action: "Mirror top-performing social proof on homepage hero — same photos, reviews, and tone buyers already trust.",
      expectedImpact: "+10–18% conversion from social traffic",
    });
  } else if (trust.strongerChannel === "website") {
    recs.push({
      id: "sm-trust-social",
      priority: "medium",
      title: "Extend website trust to social",
      action: "Repurpose homepage guarantees and testimonials as pinned posts and story highlights.",
      expectedImpact: "+8–12% social referral trust",
    });
  }

  return recs;
}

export function analyzeSocialMedia(business: Business): SocialMediaAnalysis {
  const presence = inferDigitalPresenceFromBusiness(business);
  const profiles = presence?.socialProfiles ?? [];
  const yourReach = totalSocialReach(profiles);
  const pickShare = buildPickShare(business, yourReach);
  const yourPickSharePercent = pickShare.find((p) => p.isYou)?.pickSharePercent ?? 0;
  const trust = analyzeTrustChannels(business, profiles);
  const dimensions = buildDimensions(business, yourReach, pickShare, trust);
  const visibilityScore = clamp(
    dimensions.reduce((s, d) => s + d.yourScore, 0) / dimensions.length,
  );
  const industryVisibilityBenchmark = 72;
  const platforms = profiles.map((p) => platformInsight(p));
  const recommendations = buildRecommendations(trust, dimensions);
  const topCompetitor = pickShare.find((p) => !p.isYou);

  const executiveSummary =
    `${business.input.businessName}'s social visibility scores ${visibilityScore}/100 (industry leaders ~${industryVisibilityBenchmark}). ` +
    `In a simulated local comparison, you're picked ${yourPickSharePercent}% of the time` +
    (topCompetitor ? ` vs ${topCompetitor.name} at ${topCompetitor.pickSharePercent}%` : "") +
    `. Trust: ${trust.strongerChannel === "balanced" ? "website and social are balanced" : trust.strongerChannel === "website" ? "website builds more trust than social" : "social builds more trust than website"} — ${trust.websiteTrustScore}/100 web vs ${trust.socialTrustScore}/100 social.`;

  return {
    analyzedAt: new Date().toISOString(),
    visibilityScore,
    industryVisibilityBenchmark,
    pickShare,
    yourPickSharePercent,
    trust,
    dimensions,
    platforms,
    recommendations,
    executiveSummary,
  };
}

export function getOrAnalyzeSocialMedia(business: Business): SocialMediaAnalysis {
  return business.socialMediaAnalysis ?? analyzeSocialMedia(business);
}
