import type { BrandProfile, Project } from "@/types/workflow";
import type { WebsiteIntelligence } from "@/lib/context/website-intelligence";
import {
  detectSolutionCategory,
  resolveDynamicProductConfig,
  solutionToBrandVertical,
} from "@/lib/generation/dynamic-product-config";

/** Product vertical — inferred from scraped website content when available. */
export type BrandVertical = "fax" | "sms" | "email" | "generic";

export type FeatureIconKind = "challenge" | "solution" | "impact" | "service" | "benefit";

export interface BrandVisualStyle {
  primaryColor: string;
  accentColor: string;
  lightBg: string;
  tagline: string;
  website: string;
  contactEmail: string;
  contactPhone: string;
  heroHeadline: string[];
  features: Array<{ label: string; detail: string; accent: boolean; icon: FeatureIconKind }>;
  footerBenefits: string[];
  ctaLine: string;
  ctaSubline: string;
  vertical: BrandVertical;
  primaryService: string;
  productVisualHint: string;
  /** Extended multi-solution category (dnc, dialer, call_tracking, …). */
  solutionCategory: string;
  /** @deprecated use vertical === "fax" */
  isEfaxBrand: boolean;
}

const DEFAULT_COLORS = { primary: "#1e3a5f", accent: "#e87121" };

function firstSentence(text: string, maxLen = 72): string {
  const sentence = text.split(/[.!?]/)[0]?.trim() || text.trim();
  if (!sentence) return "";
  return sentence.length > maxLen ? `${sentence.slice(0, maxLen - 1).trim()}…` : sentence;
}

function hookLabel(text: string, maxLen = 28): string {
  const cleaned = text.trim();
  if (!cleaned) return "";
  const words = cleaned.split(/\s+/).filter(Boolean);
  return words.slice(0, 4).join(" ").slice(0, maxLen).toUpperCase();
}

function serviceLabel(text: string, maxLen = 24): string {
  const words = text.trim().split(/\s+/).filter(Boolean);
  return words.slice(0, 3).join(" ").slice(0, maxLen).toUpperCase();
}

/** Detect vertical — service/portfolio first; never lock on brand name alone (e.g. B2BEFAX ≠ always fax). */
export function detectBrandVertical(
  brand: BrandProfile,
  project: Project,
  website?: WebsiteIntelligence | null,
): BrandVertical {
  const category = detectSolutionCategory({ brand, project, website });
  return solutionToBrandVertical(category);
}

function serviceDisplayLabel(text: string, maxLen = 36): string {
  const trimmed = text.trim();
  if (!trimmed) return "";
  if (trimmed.length <= maxLen) return trimmed;
  const cut = trimmed.slice(0, maxLen);
  const lastSpace = cut.lastIndexOf(" ");
  return `${(lastSpace > 20 ? cut.slice(0, lastSpace) : cut).trim()}…`;
}

function iconForServiceLabel(label: string, index: number): FeatureIconKind {
  const hay = label.toLowerCase();
  if (/secure|confidential|compliance|trust|encrypt/.test(hay)) return "benefit";
  if (/access|anywhere|cloud|mobile|instant/.test(hay)) return "solution";
  if (/cost|grow|scale|business|result/.test(hay)) return "impact";
  if (/send|receive|broadcast|deliver|fax|sms|email/.test(hay)) return "service";
  return (["service", "benefit", "solution", "impact"] as FeatureIconKind[])[index % 4]!;
}

function resolveContactEmail(
  brand: BrandProfile,
  _websiteDisplay: string,
  website?: WebsiteIntelligence | null,
): string {
  const fromBrand = brand.contactEmail?.trim() ?? "";
  if (fromBrand) return fromBrand.toLowerCase();

  const fromScrape = website?.contactEmail?.trim() ?? "";
  if (fromScrape) return fromScrape.toLowerCase();

  // No invented info@ domain — email is optional until set on brand profile or scraped.
  return "";
}

function resolveContactPhone(
  brand: BrandProfile,
  website?: WebsiteIntelligence | null,
): string {
  const fromBrand = brand.contactPhone?.trim() ?? "";
  if (fromBrand) return fromBrand;
  return website?.contactPhone?.trim() ?? "";
}

function buildHeroHeadline(headline: string, tagline: string): string[] {
  const source = headline.trim() || tagline.trim();
  if (!source) return [];
  const upper = source.toUpperCase();
  const byPeriod = upper.split(/\.\s+/).filter(Boolean);
  if (byPeriod.length >= 2) {
    return [byPeriod[0]!.endsWith(".") ? byPeriod[0]! : `${byPeriod[0]!}.`, byPeriod.slice(1).join(". ")];
  }
  const words = upper.split(/\s+/).filter(Boolean);
  if (words.length <= 5) return [upper];
  const mid = Math.ceil(words.length / 2);
  return [words.slice(0, mid).join(" "), words.slice(mid).join(" ")];
}

function looksLikeSloganLabel(text: string): boolean {
  const t = text.trim();
  if (t.length > 42) return true;
  if (/market your|revolutioniz|best ever|next level/i.test(t)) return true;
  if ((t.match(/-/g) || []).length >= 2) return true;
  return false;
}

function capabilityFeatureDefaults(vertical: BrandVertical): BrandVisualStyle["features"] {
  if (vertical === "fax") {
    return [
      { label: "SECURE DELIVERY", detail: "Encrypt and protect high-stakes business documents.", accent: false, icon: "benefit" },
      { label: "BROADCAST REACH", detail: "Send to many recipients without inbox noise.", accent: true, icon: "service" },
      { label: "AUDIT TRAILS", detail: "Keep defensible delivery records automatically.", accent: false, icon: "solution" },
      { label: "COMPLIANT OUTREACH", detail: "Support healthcare, legal, insurance, and finance handoffs.", accent: true, icon: "impact" },
    ];
  }
  if (vertical === "email") {
    return [
      { label: "INBOX PLACEMENT", detail: "Protect deliverability with authenticated sending.", accent: false, icon: "benefit" },
      { label: "SEGMENTATION", detail: "Reach the right audience with relevant messaging.", accent: true, icon: "service" },
      { label: "AUTOMATION", detail: "Run drip workflows without manual follow-ups.", accent: false, icon: "solution" },
      { label: "CAMPAIGN INSIGHT", detail: "Track opens, clicks, and bounce trends clearly.", accent: true, icon: "impact" },
    ];
  }
  if (vertical === "sms") {
    return [
      { label: "HIGH-VOLUME SMS", detail: "Deliver messages at scale with delivery control.", accent: false, icon: "service" },
      { label: "COMPLIANCE GUARDS", detail: "Reduce risk on regulated outreach traffic.", accent: true, icon: "benefit" },
      { label: "SMART ROUTING", detail: "Keep urgent notices moving to the right recipients.", accent: false, icon: "solution" },
      { label: "RESPONSE LIFT", detail: "Improve reply rates with timely, clear messaging.", accent: true, icon: "impact" },
    ];
  }
  return [
    { label: "RELIABLE WORKFLOWS", detail: "Reduce operational friction for everyday teams.", accent: false, icon: "solution" },
    { label: "SECURE EXCHANGE", detail: "Protect sensitive business communication.", accent: true, icon: "benefit" },
    { label: "FASTER HANDOFFS", detail: "Keep documents and decisions moving.", accent: false, icon: "service" },
    { label: "CLEAR ROI", detail: "Tie communication spend to measurable outcomes.", accent: true, icon: "impact" },
  ];
}

/** Image/card features — short human capability labels (never dump scraped slogans). */
function featuresFromSources(input: {
  brand: BrandProfile;
  story?: { problem?: string; impact?: string; brandResponse?: string };
  website?: WebsiteIntelligence | null;
  primaryService: string;
  vertical: BrandVertical;
}): BrandVisualStyle["features"] {
  const { website, vertical } = input;
  const features: BrandVisualStyle["features"] = [];

  for (const service of website?.services ?? []) {
    if (features.length >= 4) break;
    const rawLabel = service.label?.trim() || "";
    if (!rawLabel || looksLikeSloganLabel(rawLabel)) continue;
    const label = serviceDisplayLabel(rawLabel);
    if (!label || looksLikeSloganLabel(label)) continue;
    if (features.some((f) => f.label.toLowerCase() === label.toLowerCase())) continue;
    const detail = firstSentence(service.detail || "", 72);
    features.push({
      label,
      detail: detail && !looksLikeSloganLabel(detail) ? detail : `Practical capability for ${label.toLowerCase()}.`,
      accent: features.length % 2 === 1,
      icon: iconForServiceLabel(label, features.length),
    });
  }

  for (const benefit of website?.benefits ?? []) {
    if (features.length >= 4) break;
    if (!benefit.trim() || looksLikeSloganLabel(benefit)) continue;
    const label = serviceDisplayLabel(benefit, 28);
    if (!label || features.some((f) => f.label.toLowerCase() === label.toLowerCase())) continue;
    features.push({
      label,
      detail: firstSentence(benefit, 72),
      accent: features.length % 2 === 1,
      icon: "benefit",
    });
  }

  const defaults = capabilityFeatureDefaults(vertical);
  for (const def of defaults) {
    if (features.length >= 4) break;
    if (features.some((f) => f.label.toLowerCase() === def.label.toLowerCase())) continue;
    features.push(def);
  }

  return features.slice(0, 4);
}

function footerBenefitsFromSources(
  impact: string | undefined,
  website?: WebsiteIntelligence | null,
): string[] {
  if (website?.benefits?.length) return website.benefits.slice(0, 4);
  const text = (impact ?? "").toLowerCase();
  const derived: string[] = [];
  if (/cost|save|budget/.test(text)) derived.push("REDUCE COSTS");
  if (/secure|compliance|trust/.test(text)) derived.push("STAY SECURE");
  if (/fast|time|instant/.test(text)) derived.push("SAVE TIME");
  if (/grow|scale|reach|result/.test(text)) derived.push("GROW MORE");
  return derived.slice(0, 4);
}

/**
 * Resolve brand visuals from website scrape + brand profile + posting context.
 * Static vertical templates are not used — only live company data.
 */
export function resolveBrandVisualStyle(
  brand: BrandProfile,
  project: Project,
  story?: { problem?: string; impact?: string; brandResponse?: string },
  website?: WebsiteIntelligence | null,
): BrandVisualStyle {
  const product = resolveDynamicProductConfig({
    brand,
    project,
    website,
    problem: story?.problem,
    impact: story?.impact,
    brandResponse: story?.brandResponse,
  });
  const vertical = solutionToBrandVertical(product.solutionCategory);
  const primaryColor = website?.themeColor || DEFAULT_COLORS.primary;
  const accentColor = website?.accentColor || DEFAULT_COLORS.accent;

  const companyName = brand.companyName?.trim() || website?.companyName?.trim() || project.name;
  const brandTagline = brand.tagline?.trim() || "";
  const scrapedTagline = website?.tagline?.trim() || "";
  const taglineRaw = (() => {
    const candidate = brandTagline || scrapedTagline || "";
    if (!candidate || looksLikeSloganLabel(candidate) || /market you business|revolutioniz/i.test(candidate)) {
      return product.subheadline.slice(0, 72) || `${companyName} — practical business communication`;
    }
    return candidate;
  })();

  const websiteUrl = project.website?.trim() || website?.url || "";
  const websiteDisplay = websiteUrl.replace(/^https?:\/\//i, "").replace(/\/$/, "");

  const brandResponse = story?.brandResponse?.trim() ?? "";
  const impact = story?.impact?.trim() ?? "";
  const primaryService = product.solutionName;

  const resolvedFeatures = featuresFromSources({
    brand,
    story,
    website,
    primaryService,
    vertical,
  });

  // Dynamic product headline — never hardcode "B2B E-FAXING" when another solution is active.
  const heroHeadline = buildHeroHeadline(product.primaryHeadline, companyName);

  return {
    primaryColor,
    accentColor,
    lightBg: "#f8fafc",
    tagline: taglineRaw.slice(0, 72),
    website: websiteDisplay,
    contactEmail: resolveContactEmail(brand, websiteDisplay, website),
    contactPhone: resolveContactPhone(brand, website),
    heroHeadline,
    features: resolvedFeatures,
    footerBenefits: footerBenefitsFromSources(impact, website),
    ctaLine: brandResponse && !looksLikeSloganLabel(brandResponse)
      ? firstSentence(brandResponse, 36).toUpperCase()
      : "LEARN MORE",
    ctaSubline: product.primaryValueProp.slice(0, 48).toUpperCase() || "SECURE OPERATIONS.",
    vertical,
    primaryService,
    productVisualHint: product.modernVisualDirection,
    solutionCategory: product.solutionCategory,
    isEfaxBrand: product.solutionCategory === "fax",
  };
}

/** AI image prompt — minimalist human editorial (photo + typography), white-label. */
export function buildSaaSMarketingImageStyleBlock(
  style: BrandVisualStyle,
  company: string,
  industry: string,
): string {
  const website = style.website?.replace(/^https?:\/\//i, "").replace(/\/$/, "") || "";
  const contactParts = [
    website ? `website ${website}` : "",
    style.contactPhone ? `phone ${style.contactPhone}` : "",
    style.contactEmail ? `email ${style.contactEmail}` : "",
  ].filter(Boolean);
  const cta = style.ctaLine?.trim().slice(0, 18).toUpperCase() || "LEARN MORE";

  return [
    "STYLE LOCK v2026-H2 HUMAN-EDITORIAL (must refresh on every regenerate — ignore legacy flyer layouts):",
    `Brand: ${company}. Offer: ${style.primaryService || industry}. Navy ${style.primaryColor} + accent ${style.accentColor}.`,
    "Layout: Left ~⅓ candid photoreal office portrait (natural light, soft bg). Right ~⅔ clean off-white typography block.",
    "Copy zones only: logo + short tagline, ONE bold navy headline, ONE short subheadline, orange LEARN MORE + URL. No 4-row feature dumps.",
    `CTA: "${cta}".`,
    `Contact lock: ${contactParts.join(", ") || "website only"}. Never invent info@ emails.`,
    "HARD BAN (legacy AI look): flat vector silhouettes, speech-bubble truncated text, icon-grid flyers, fax-machine/hardware heroes, cloud overlays, dotted world maps, repetitive slogan labels, AI-stock poses.",
    "Must look like high-end editorial B2B photography + clean design — not a templated marketing SVG.",
  ].join(" ");
}

/** Right-panel caption from scraped primary service or company name. */
export function verticalPanelLabel(style: BrandVisualStyle): string {
  const label = style.primaryService || style.tagline || "OUR SERVICES";
  return label.slice(0, 28).toUpperCase();
}

/**
 * Prefer branded 1080×1080 social banner when brand assets exist so regenerate
 * always produces a complete layout (logo, headline, bullets, CTA, contact).
 * AI providers remain in the chain as fallback when branding is thin.
 */
export function shouldPreferBrandedTemplate(input: {
  logoDataUrl?: string | null;
  problemTheme?: string;
  brandResponse?: string;
  tagline?: string;
  websiteOk?: boolean;
  website?: string;
  hasServices?: boolean;
  contactPhone?: string;
  contactEmail?: string;
}): boolean {
  if (input.logoDataUrl?.trim()) return true;
  if (input.websiteOk || input.website?.trim()) return true;
  if (input.hasServices) return true;
  if (input.contactPhone?.trim() || input.contactEmail?.trim()) return true;
  if (input.problemTheme?.trim() && input.brandResponse?.trim()) return true;
  return false;
}
