import { inferDigitalPresenceFromBusiness } from "@/lib/demo-digital-presence";
import type {
  Business,
  IndustryWebsiteBenchmark,
  WebsiteAestheticAnalysis,
  WebsiteAestheticDimension,
  WebsiteAestheticRecommendation,
  WebsiteDimensionScore,
} from "@/lib/types";

const DIMENSION_LABELS: Record<WebsiteAestheticDimension, string> = {
  typography: "Typography & readability",
  colorPalette: "Color & brand feel",
  layout: "Layout & hierarchy",
  imagery: "Photography & visuals",
  trustSignals: "Trust & social proof",
  mobileExperience: "Mobile experience",
  conversionPath: "Conversion path",
};

interface IndustryTemplate {
  benchmarkScore: number;
  topPerformerTraits: string[];
  referenceProfiles: string[];
  dimensionNotes: Record<WebsiteAestheticDimension, { top: string; typicalGap: string }>;
  patterns: Array<{
    dimension: WebsiteAestheticDimension;
    title: string;
    pattern: string;
    preserve: string;
    impact: string;
  }>;
}

function resolveIndustryKey(business: Business): string {
  const cat = business.input.industryCategory?.toLowerCase() ?? "";
  const ind = business.input.industry?.toLowerCase() ?? "";
  if (cat.includes("home") || ind.includes("roof") || ind.includes("hvac") || ind.includes("landscape")) {
    return "home-services";
  }
  if (cat.includes("beauty") || ind.includes("med spa") || ind.includes("spa")) return "beauty";
  if (cat.includes("saas") || ind.includes("saas") || ind.includes("software")) return "saas";
  if (cat.includes("hospitality") || ind.includes("restaurant") || ind.includes("food")) return "hospitality";
  if (cat.includes("fitness") || ind.includes("fitness") || ind.includes("gym")) return "fitness";
  if (ind.includes("dental")) return "dental";
  if (cat.includes("health") || ind.includes("medical") || ind.includes("supply")) return "healthcare";
  if (cat.includes("real estate") || ind.includes("realty") || ind.includes("real estate")) return "real-estate";
  return "general";
}

const INDUSTRY_TEMPLATES: Record<string, IndustryTemplate> = {
  "home-services": {
    benchmarkScore: 82,
    topPerformerTraits: [
      "Hero with local proof + emergency/seasonal urgency above the fold",
      "Before/after galleries with real crew and job-site photos",
      "Transparent pricing cues or guarantee badges (not hidden fees)",
      "Click-to-call and book-now sticky on mobile",
      "Google review count and trade badges near primary CTA",
    ],
    referenceProfiles: [
      "Top 10% local contractors by review volume in your metro",
      "Category leaders with 4.7★+ and conversion-focused homepages",
    ],
    dimensionNotes: {
      typography: { top: "Bold sans-serif headlines, scannable bullet benefits", typicalGap: "Dense paragraphs, weak headline hierarchy" },
      colorPalette: { top: "Trust blues + action orange/green CTAs, high contrast", typicalGap: "Muted palette, CTA blends into background" },
      layout: { top: "Service areas, offers, and proof in first viewport", typicalGap: "Company history before customer outcome" },
      imagery: { top: "Real job photos, team uniforms, local landmarks", typicalGap: "Stock photos, no proof of local work" },
      trustSignals: { top: "Review count, licenses, guarantees above fold", typicalGap: "Testimonials buried on secondary pages" },
      mobileExperience: { top: "Tap-to-call, sticky book button, fast load", typicalGap: "Desktop-first layout, slow mobile forms" },
      conversionPath: { top: "Single primary CTA per page + short form", typicalGap: "Multiple competing CTAs, long quote forms" },
    },
    patterns: [
      {
        dimension: "layout",
        title: "Lead with outcome, not company history",
        pattern: "Top home-service sites open with the problem you solve + local proof in 5 seconds.",
        preserve: "Keep your crew story and values — move them below the fold, not in the hero.",
        impact: "+12–18% form completion",
      },
      {
        dimension: "imagery",
        title: "Swap stock for real job-site photography",
        pattern: "Highest-converting contractors show before/after and team on every service page.",
        preserve: "Use your own brand colors and logo treatment on photo overlays — don't mimic competitor layouts.",
        impact: "+8–15% trust on mobile",
      },
      {
        dimension: "trustSignals",
        title: "Surface reviews and guarantees at decision points",
        pattern: "Top performers repeat Google rating + guarantee near every CTA.",
        preserve: "Quote your actual differentiator (e.g. 48-hour estimate, no surprise fees) — not generic 'best in town'.",
        impact: "+10% call-to-book rate",
      },
    ],
  },
  beauty: {
    benchmarkScore: 85,
    topPerformerTraits: [
      "Luxury-minimal layout with high-quality treatment photography",
      "Online booking above the fold with provider credentials",
      "Before/after galleries with consent-forward presentation",
      "Membership / package tiers with clear value ladder",
      "Instagram-style visual rhythm without looking like a template clone",
    ],
    referenceProfiles: [
      "Top med spas by booking conversion in your market",
      "Premium aesthetic clinics with 4.8★+ and strong social follow-through",
    ],
    dimensionNotes: {
      typography: { top: "Elegant serif or refined sans pairing, generous whitespace", typicalGap: "Crowded menus, promotional clutter" },
      colorPalette: { top: "Soft neutrals + one accent (rose gold, sage, charcoal)", typicalGap: "Too many accent colors, discount-banner fatigue" },
      layout: { top: "Treatment menu as visual cards with price anchors", typicalGap: "PDF menu downloads, unclear booking path" },
      imagery: { top: "Consistent lighting, real patients (with permission), studio shots", typicalGap: "Mixed quality, over-filtered stock" },
      trustSignals: { top: "Injector credentials, reviews, safety protocols visible", typicalGap: "Credentials on About page only" },
      mobileExperience: { top: "Book in 2 taps, treatment photos optimized", typicalGap: "Phone-only booking via call, heavy pages" },
      conversionPath: { top: "Treatment → book → deposit or consult request", typicalGap: "Contact form with no treatment context" },
    },
    patterns: [
      {
        dimension: "colorPalette",
        title: "Refine palette to premium neutrals + one signature accent",
        pattern: "Top med spas limit to 2–3 colors and let photography carry emotion.",
        preserve: "Choose accent from your existing brand (logo, studio interior) — don't copy a competitor's rose-gold trend.",
        impact: "+14% perceived premium tier",
      },
      {
        dimension: "conversionPath",
        title: "Treatment-specific booking paths",
        pattern: "Best performers let visitors book Botox, laser, or consult from the homepage card grid.",
        preserve: "Name packages in your voice (e.g. 'Glow Membership') — adopt structure, not competitor offer names.",
        impact: "+20% online bookings",
      },
    ],
  },
  saas: {
    benchmarkScore: 88,
    topPerformerTraits: [
      "Clear ICP headline + product screenshot in first viewport",
      "Social proof logos and quantified outcomes (not vague claims)",
      "Interactive demo or free trial CTA above fold",
      "Comparison and security pages for enterprise trust",
      "Docs-style clarity — scannable, not marketing fluff",
    ],
    referenceProfiles: [
      "Category leaders on G2/Capterra with highest trial-to-paid conversion",
      "Product-led SaaS sites with sub-3s load and clear ICP messaging",
    ],
    dimensionNotes: {
      typography: { top: "System fonts or modern grotesk, strong type scale", typicalGap: "Wall of text, vague hero headline" },
      colorPalette: { top: "Primary brand + neutral UI grays, one CTA color", typicalGap: "Gradient overload, unclear focus" },
      layout: { top: "Problem → product → proof → pricing path", typicalGap: "Feature lists without outcomes" },
      imagery: { top: "Real product UI, annotated screenshots", typicalGap: "Abstract illustrations only" },
      trustSignals: { top: "Customer logos, SOC2/GDPR badges, case study metrics", typicalGap: "Generic 'trusted by thousands'" },
      mobileExperience: { top: "Readable screenshots, sticky trial CTA", typicalGap: "Broken mobile nav, tiny screenshots" },
      conversionPath: { top: "Trial or demo with minimal fields", typicalGap: "Contact sales only on homepage" },
    },
    patterns: [
      {
        dimension: "layout",
        title: "Outcome-first hero with product proof",
        pattern: "Top SaaS sites state who it's for, what changes, and show the product immediately.",
        preserve: "Keep your category POV and voice — adopt clarity, not competitor taglines.",
        impact: "+25% demo requests",
      },
      {
        dimension: "trustSignals",
        title: "Quantify proof near primary CTA",
        pattern: "Leaders use specific metrics ('cut onboarding 40%') not adjectives.",
        preserve: "Use your real customer outcomes and logo permissions — never fabricate logos.",
        impact: "+18% trial starts",
      },
    ],
  },
  hospitality: {
    benchmarkScore: 80,
    topPerformerTraits: [
      "Mouth-watering food photography with consistent styling",
      "Reservations and catering CTAs equally visible",
      "Menu as browsable web experience, not PDF",
      "Story-driven About without blocking booking",
      "Local SEO pages (neighborhood, events, private dining)",
    ],
    referenceProfiles: [
      "Top OpenTable performers in your cuisine category",
      "Farm-to-table and event venues with highest direct booking share",
    ],
    dimensionNotes: {
      typography: { top: "Readable menu type, distinctive display font for headers only", typicalGap: "Tiny menu text, PDF-only menus" },
      colorPalette: { top: "Warm earth tones or clean bistro white space", typicalGap: "Clashing promo banners" },
      layout: { top: "Reserve + menu + location in first scroll", typicalGap: "Long story before reservation link" },
      imagery: { top: "Professional dish and ambiance shots, seasonal updates", typicalGap: "Dark phone photos, inconsistent crops" },
      trustSignals: { top: "Press, awards, review snippets near reserve button", typicalGap: "Yelp link only in footer" },
      mobileExperience: { top: "One-tap reservation, click-to-call", typicalGap: "PDF menus on mobile" },
      conversionPath: { top: "OpenTable/embed + catering inquiry split paths", typicalGap: "Single contact form for everything" },
    },
    patterns: [
      {
        dimension: "imagery",
        title: "Invest in consistent dish photography",
        pattern: "Top restaurants refresh hero imagery seasonally and match Instagram quality.",
        preserve: "Show your farm partners and kitchen voice — your story is the differentiator.",
        impact: "+15% reservation clicks",
      },
      {
        dimension: "conversionPath",
        title: "Split dine-in vs catering journeys",
        pattern: "High performers route corporate catering to dedicated landing pages.",
        preserve: "Name your packages (Chef's Table, Harvest Table) — don't copy competitor offer titles.",
        impact: "+22% catering inquiries",
      },
    ],
  },
  fitness: {
    benchmarkScore: 79,
    topPerformerTraits: [
      "Transformation and community photos (real members)",
      "Simple membership tiers with trial or intro offer",
      "Class schedule embed with mobile-first booking",
      "Corporate wellness page for B2B revenue",
      "Sticky 'Start trial' on mobile",
    ],
    referenceProfiles: [
      "Studios with highest intro-offer conversion in your metro",
      "Boutique gyms with strong retention and clear tier pricing",
    ],
    dimensionNotes: {
      typography: { top: "Energetic but readable — bold headlines, short blocks", typicalGap: "Aggressive sales copy, hard to scan" },
      colorPalette: { top: "High-energy accent on dark or clean white base", typicalGap: "Too many promo colors" },
      layout: { top: "Trial CTA + schedule + social proof in hero zone", typicalGap: "Equipment list before benefit" },
      imagery: { top: "Real members mid-workout, diverse representation", typicalGap: "Stock fitness models only" },
      trustSignals: { top: "Reviews, trainer creds, results stats", typicalGap: "Testimonials on separate page" },
      mobileExperience: { top: "Fast trial signup, tap-to-call", typicalGap: "Multi-step forms on mobile" },
      conversionPath: { top: "Intro offer → schedule → pay or book", typicalGap: "Call-only membership sales" },
    },
    patterns: [
      {
        dimension: "imagery",
        title: "Show your actual community, not stock gym shots",
        pattern: "Top studios feature member transformations and class energy.",
        preserve: "Your coaching philosophy and brand colors stay — adopt authenticity, not another gym's look.",
        impact: "+12% trial signups",
      },
    ],
  },
  dental: {
    benchmarkScore: 83,
    topPerformerTraits: [
      "Anxiety-reducing calm design with warm photography",
      "New patient offer and online scheduling prominent",
      "Doctor credentials and technology on homepage",
      "Insurance/financing clarity without clutter",
      "Before/after smile galleries with ethical presentation",
    ],
    referenceProfiles: [
      "Top Google-rated dental groups by new patient volume",
      "Cosmetic-focused practices with highest consult conversion",
    ],
    dimensionNotes: {
      typography: { top: "Friendly, accessible type — no clinical coldness", typicalGap: "Small text, institutional feel" },
      colorPalette: { top: "Calm blues/teals + warm accents", typicalGap: "Harsh clinical white, no warmth" },
      layout: { top: "New patient path + services grid above fold", typicalGap: "Staff bios before patient benefits" },
      imagery: { top: "Smiling team, modern operatory, welcoming reception", typicalGap: "Outdated office photos" },
      trustSignals: { top: "Reviews, affiliations, sedation options highlighted", typicalGap: "Credentials buried" },
      mobileExperience: { top: "Book appointment + click-to-call sticky", typicalGap: "Forms that don't work on mobile" },
      conversionPath: { top: "Service-specific consult requests", typicalGap: "Generic contact form" },
    },
    patterns: [
      {
        dimension: "trustSignals",
        title: "Lead with patient comfort proof",
        pattern: "Top practices pair reviews with 'never rushed' / sedation messaging at CTAs.",
        preserve: "Use your real care philosophy — adopt placement, not competitor slogans.",
        impact: "+16% new patient forms",
      },
    ],
  },
  healthcare: {
    benchmarkScore: 81,
    topPerformerTraits: [
      "B2B clarity — catalog, compliance, account login paths",
      "Professional photography and clean data tables",
      "Case studies with quantified outcomes for buyers",
      "Request quote / RFP flows with minimal friction",
      "Trust badges (ISO, FDA, GPO) near conversion",
    ],
    referenceProfiles: [
      "Top medical supply distributors by digital quote volume",
      "B2B healthcare vendors with highest procurement engagement",
    ],
    dimensionNotes: {
      typography: { top: "Clean sans, scannable spec tables", typicalGap: "Consumer-style marketing on B2B buyers" },
      colorPalette: { top: "Professional blues/grays, restrained accents", typicalGap: "Flashy consumer promotions" },
      layout: { top: "Product category → compliance → quote path", typicalGap: "Blog-first layout for buyers" },
      imagery: { top: "Product in context, warehouse/delivery proof", typicalGap: "Generic medical stock" },
      trustSignals: { top: "Certifications, client logos, compliance docs", typicalGap: "Trust content in PDF downloads only" },
      mobileExperience: { top: "Readable tables, quick quote tap", typicalGap: "Desktop-only ordering" },
      conversionPath: { top: "Account request + volume pricing calculator", typicalGap: "Phone-only ordering CTA" },
    },
    patterns: [
      {
        dimension: "conversionPath",
        title: "Procurement-ready quote flows",
        pattern: "Leaders offer volume pricing tools and RFP upload on homepage paths.",
        preserve: "Your SLA and local delivery story — structure from leaders, message from you.",
        impact: "+20% qualified B2B leads",
      },
    ],
  },
  "real-estate": {
    benchmarkScore: 84,
    topPerformerTraits: [
      "High-end photography and neighborhood lifestyle imagery",
      "IDX search with saved searches / alerts",
      "Agent credibility + recent sales proof",
      "Investor or luxury niche pages (not generic brokerage)",
      "Market report lead magnets",
    ],
    referenceProfiles: [
      "Top luxury and investor teams by organic lead share",
      "Brokerages with highest time-on-site and saved search rates",
    ],
    dimensionNotes: {
      typography: { top: "Editorial serif + clean sans for listings", typicalGap: "Template brokerage look, no niche voice" },
      colorPalette: { top: "Sophisticated neutrals, gold or navy accents", typicalGap: "Default franchise palette" },
      layout: { top: "Search + niche value prop + proof in hero", typicalGap: "Agent headshot wall before search" },
      imagery: { top: "Professional listing photos, neighborhood guides", typicalGap: "Low-quality listing imports" },
      trustSignals: { top: "Sold stats, client stories, market expertise", typicalGap: "Generic 'years of experience'" },
      mobileExperience: { top: "Fast search, save listing, tap-to-call agent", typicalGap: "Slow IDX on mobile" },
      conversionPath: { top: "Search → save → consult / investor list signup", typicalGap: "Contact form without search" },
    },
    patterns: [
      {
        dimension: "layout",
        title: "Niche hub above generic brokerage layout",
        pattern: "Top teams lead with investor or luxury niche, not 'welcome to our site'.",
        preserve: "Your neighborhood expertise and team story — adopt structure from leaders, not their branding.",
        impact: "+18% investor/luxury leads",
      },
    ],
  },
  general: {
    benchmarkScore: 78,
    topPerformerTraits: [
      "Clear value proposition in first 5 seconds",
      "Social proof near primary CTA",
      "Mobile-first layout with fast load",
      "Consistent visual identity across pages",
      "Single focused conversion path per page",
    ],
    referenceProfiles: ["Top-performing businesses in your category by conversion and reviews"],
    dimensionNotes: {
      typography: { top: "Strong hierarchy, scannable headlines", typicalGap: "Unclear headline, dense blocks" },
      colorPalette: { top: "2–3 colors, high-contrast CTA", typicalGap: "Too many competing colors" },
      layout: { top: "Outcome → proof → action", typicalGap: "About-first homepage" },
      imagery: { top: "Authentic brand photography", typicalGap: "Generic stock imagery" },
      trustSignals: { top: "Reviews and guarantees visible", typicalGap: "Proof buried in footer" },
      mobileExperience: { top: "Sticky CTA, readable tap targets", typicalGap: "Desktop-only design" },
      conversionPath: { top: "One primary CTA per page", typicalGap: "Multiple competing actions" },
    },
    patterns: [
      {
        dimension: "layout",
        title: "Outcome-first homepage structure",
        pattern: "Top sites in any category lead with customer outcome, not company history.",
        preserve: "Your brand voice and visual identity stay — borrow structure, not aesthetics wholesale.",
        impact: "+10–15% engagement",
      },
    ],
  },
};

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

function scoreFromBusiness(business: Business, dimension: WebsiteAestheticDimension): number {
  const base = business.brandScore.conversion;
  const hasWebsite = Boolean(business.input.websiteUrl?.trim());
  const weaknessText = [
    ...business.profile.weaknesses,
    ...business.competitors.flatMap((c) => c.weaknesses),
  ].join(" ").toLowerCase();

  let score = hasWebsite ? base : base - 25;
  const gaps: Partial<Record<WebsiteAestheticDimension, string[]>> = {
    typography: ["dated", "wall of text", "unclear"],
    colorPalette: ["dated", "generic", "template"],
    layout: ["buried", "history", "clutter"],
    imagery: ["stock", "outdated", "dark phone", "generic"],
    trustSignals: ["reviews", "proof", "testimonial", "rating"],
    mobileExperience: ["mobile", "slow", "booking", "form"],
    conversionPath: ["cta", "form", "booking", "contact"],
  };

  const keywords = gaps[dimension] ?? [];
  const hitCount = keywords.filter((k) => weaknessText.includes(k)).length;
  score -= hitCount * 4;

  if (business.digitalPresence?.socialProfiles.length) score += 2;
  if (dimension === "trustSignals" && business.brandScore.trust > 75) score += 5;
  if (dimension === "conversionPath" && business.brandScore.conversion > 70) score += 3;

  return clamp(score + (dimension === "mobileExperience" ? -2 : 0));
}

function buildIdentityAnchors(business: Business): string[] {
  const anchors = [
    `Brand positioning: ${business.profile.brandPositioning}`,
    business.profile.strengths[0] ? `Core strength — ${business.profile.strengths[0]}` : "",
    business.input.revenueGoal ? `Growth goal — ${business.input.revenueGoal}` : "",
    `Maintain your local identity in ${business.input.location} — never copy a competitor's look verbatim`,
  ].filter(Boolean);

  return anchors.slice(0, 4);
}

function buildRecommendations(
  business: Business,
  template: IndustryTemplate,
  dimensions: WebsiteDimensionScore[],
): WebsiteAestheticRecommendation[] {
  const sorted = [...dimensions].sort((a, b) => b.gap - a.gap);
  const topGaps = sorted.filter((d) => d.gap > 5).slice(0, 3);
  const recs: WebsiteAestheticRecommendation[] = [];

  topGaps.forEach((dim, i) => {
    const pattern = template.patterns.find((p) => p.dimension === dim.dimension) ?? template.patterns[0];
    if (!pattern) return;
    recs.push({
      id: `wa-${dim.dimension}`,
      priority: i === 0 ? "high" : i === 1 ? "medium" : "low",
      category: dim.dimension,
      title: pattern.title,
      action: `Update ${DIMENSION_LABELS[dim.dimension].toLowerCase()}: ${dim.topPerformerNote.split(".")[0]}.`,
      industryPattern: pattern.pattern,
      preserveIndependence: pattern.preserve,
      estimatedImpact: pattern.impact,
    });
  });

  recs.push({
    id: "wa-identity",
    priority: "high",
    category: "identity",
    title: "Adopt patterns, not competitor clones",
    action: `Refresh aesthetics using top ${business.input.industry} performer layouts while keeping your name, colors, and story distinct.`,
    industryPattern: template.topPerformerTraits.slice(0, 2).join(" "),
    preserveIndependence: `Never copy a competitor's logo, palette, or tagline. Use industry best practices as a scaffold — ${business.input.businessName}'s voice and proof stay unique.`,
    estimatedImpact: "Protects brand independence while closing conversion gap",
  });

  return recs;
}

export function analyzeWebsiteAesthetics(business: Business): WebsiteAestheticAnalysis {
  const presence = inferDigitalPresenceFromBusiness(business);
  const websiteUrl = presence?.websiteUrl ?? business.input.websiteUrl ?? "";
  const industryKey = resolveIndustryKey(business);
  const template = INDUSTRY_TEMPLATES[industryKey] ?? INDUSTRY_TEMPLATES.general;

  const dimensions: WebsiteDimensionScore[] = (
    Object.keys(DIMENSION_LABELS) as WebsiteAestheticDimension[]
  ).map((dimension) => {
    const yourScore = scoreFromBusiness(business, dimension);
    const topPerformerAvg = clamp(template.benchmarkScore + (dimension === "trustSignals" ? 3 : 0));
    return {
      dimension,
      label: DIMENSION_LABELS[dimension],
      yourScore,
      topPerformerAvg,
      gap: topPerformerAvg - yourScore,
      yourNote: template.dimensionNotes[dimension].typicalGap,
      topPerformerNote: template.dimensionNotes[dimension].top,
    };
  });

  const overallScore = clamp(
    dimensions.reduce((s, d) => s + d.yourScore, 0) / dimensions.length,
  );
  const industryBenchmarkScore = template.benchmarkScore;
  const independenceScore = clamp(
    70 +
      (business.profile.strengths.length >= 3 ? 10 : 0) +
      (business.profile.brandPositioning.length > 80 ? 8 : 0) -
      (overallScore < 55 ? 5 : 0),
  );

  const benchmark: IndustryWebsiteBenchmark = {
    industryLabel: business.input.industryCategory || business.input.industry,
    topPerformerTraits: template.topPerformerTraits,
    referenceProfiles: template.referenceProfiles,
  };

  const recommendations = buildRecommendations(business, template, dimensions);
  const topGap = [...dimensions].sort((a, b) => b.gap - a.gap)[0];

  const executiveSummary =
    `We analyzed ${websiteUrl || business.input.businessName}'s website against top-performing ${business.input.industry} businesses. ` +
    `Your aesthetic score is ${overallScore}/100 vs ${industryBenchmarkScore}/100 industry leaders. ` +
    `Biggest gap: ${topGap?.label ?? "layout"} (${topGap?.gap ?? 0} pts). ` +
    `Recommendations adopt proven patterns from top sellers while preserving ${business.input.businessName}'s independent brand identity — ` +
    `structure and conversion cues from leaders, your story, colors, and proof stay yours.`;

  return {
    analyzedAt: new Date().toISOString(),
    websiteUrl,
    overallScore,
    industryBenchmarkScore,
    independenceScore,
    executiveSummary,
    identityAnchors: buildIdentityAnchors(business),
    dimensions,
    benchmark,
    recommendations,
  };
}

export function getOrAnalyzeWebsiteAesthetics(business: Business): WebsiteAestheticAnalysis {
  return business.websiteAestheticAnalysis ?? analyzeWebsiteAesthetics(business);
}
